package com.betriebsratkanzlei.legalconsenthub.notification

import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Modifying
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.query.Param
import org.springframework.stereotype.Repository
import java.util.UUID

@Repository
interface NotificationRepository : JpaRepository<Notification, UUID> {
    @Query(
        """
        SELECT n FROM Notification n 
        WHERE n.organizationId = :organizationId 
        AND (n.recipient.keycloakId = :keycloakId OR n.recipient IS NULL)
        ORDER BY n.createdAt DESC
        """,
    )
    fun findByRecipientOrWithoutRecipientAndOrganizationId(
        @Param("keycloakId") keycloakId: String,
        @Param("organizationId") organizationId: String,
        pageable: Pageable,
    ): Page<Notification>

    @Query(
        """
        SELECT n FROM Notification n 
        WHERE n.organizationId = :organizationId 
        AND (n.recipient.keycloakId = :keycloakId OR n.recipient IS NULL)
        AND n.isRead = false
        ORDER BY n.createdAt DESC
        """,
    )
    fun findUnreadByRecipientOrWithoutRecipientAndOrganizationId(
        @Param("keycloakId") keycloakId: String,
        @Param("organizationId") organizationId: String,
    ): List<Notification>

    @Query(
        """
        SELECT COUNT(n) FROM Notification n 
        WHERE n.organizationId = :organizationId 
        AND (n.recipient.keycloakId = :keycloakId OR n.recipient IS NULL)
        AND n.isRead = false
        """,
    )
    fun countUnreadByRecipientOrWithoutRecipientAndOrganizationId(
        @Param("keycloakId") keycloakId: String,
        @Param("organizationId") organizationId: String,
    ): Long

    @Modifying
    @Query(
        """
        UPDATE Notification n SET n.isRead = true 
        WHERE n.organizationId = :organizationId 
        AND (n.recipient.keycloakId = :keycloakId OR n.recipient IS NULL)
        """,
    )
    fun markAllAsReadByRecipientAndOrganization(
        @Param("keycloakId") keycloakId: String,
        @Param("organizationId") organizationId: String,
    )

    @Modifying
    @Query(
        """
        DELETE FROM Notification n 
        WHERE n.organizationId = :organizationId 
        AND (n.recipient.keycloakId = :keycloakId OR n.recipient IS NULL)
        """,
    )
    fun deleteAllByRecipientAndOrganization(
        @Param("keycloakId") keycloakId: String,
        @Param("organizationId") organizationId: String,
    )
}
