package cloud.nstart.terravault.ordinis.domain.draft;

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.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;
import java.util.Optional;
import java.util.UUID;

public interface RecordDraftRepository extends JpaRepository<RecordDraft, UUID> {

  /** Pending draft на business_key (only one — exclusion constraint). */
  @Query("""
      SELECT d FROM RecordDraft d
      WHERE d.dictionaryId = :dictionaryId
        AND d.businessKey = :businessKey
        AND d.status = cloud.nstart.terravault.ordinis.domain.draft.DraftStatus.PENDING
      """)
  Optional<RecordDraft> findPendingByKey(
      @Param("dictionaryId") UUID dictionaryId,
      @Param("businessKey") String businessKey);

  /** Global queue для approver pool (D3=A). */
  @Query("""
      SELECT d FROM RecordDraft d
      WHERE d.status = cloud.nstart.terravault.ordinis.domain.draft.DraftStatus.PENDING
      ORDER BY d.submittedAt ASC
      """)
  Page<RecordDraft> findPending(Pageable pageable);

  /** Per-dictionary pending list. */
  @Query("""
      SELECT d FROM RecordDraft d
      WHERE d.dictionaryId = :dictionaryId
        AND d.status = cloud.nstart.terravault.ordinis.domain.draft.DraftStatus.PENDING
      ORDER BY d.submittedAt ASC
      """)
  List<RecordDraft> findPendingByDictionary(@Param("dictionaryId") UUID dictionaryId);

  /** Drafts автора (любого status'а) — для UI tracking "что я отправил". */
  @Query("""
      SELECT d FROM RecordDraft d
      WHERE d.makerId = :makerId
      ORDER BY d.submittedAt DESC
      """)
  Page<RecordDraft> findByMaker(@Param("makerId") String makerId, Pageable pageable);

  /** Global pending queue depth для Micrometer Gauge (Phase 4 monitoring). */
  @Query("""
      SELECT COUNT(d) FROM RecordDraft d
      WHERE d.status = cloud.nstart.terravault.ordinis.domain.draft.DraftStatus.PENDING
      """)
  long countPending();
}
