package at.procon.ted.repository;

import at.procon.ted.model.entity.ProcessedAttachment;
import at.procon.ted.model.entity.ProcessedAttachment.ProcessingStatus;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

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

/**
 * Repository for ProcessedAttachment entity.
 * Provides idempotent attachment tracking via content hash.
 *
 * @author Martin.Schweitzer@procon.co.at and claude.ai
 */
@Repository
public interface ProcessedAttachmentRepository extends JpaRepository<ProcessedAttachment, UUID> {

    /**
     * Find attachment by content hash for idempotency check.
     */
    Optional<ProcessedAttachment> findByContentHash(String contentHash);

    /**
     * Check if an attachment with given hash already exists.
     */
    boolean existsByContentHash(String contentHash);

    /**
     * Find all attachments with given processing status.
     */
    List<ProcessedAttachment> findByProcessingStatus(ProcessingStatus status);

    /**
     * Find all child attachments (extracted from a ZIP).
     */
    List<ProcessedAttachment> findByParentHash(String parentHash);

    /**
     * Find attachments by file type.
     */
    List<ProcessedAttachment> findByFileType(String fileType);

    /**
     * Count attachments by status.
     */
    long countByProcessingStatus(ProcessingStatus status);

    /**
     * Find pending attachments for retry processing.
     */
    @Query("SELECT a FROM ProcessedAttachment a WHERE a.processingStatus = 'PENDING' OR a.processingStatus = 'FAILED' ORDER BY a.receivedAt ASC")
    List<ProcessedAttachment> findPendingOrFailed();
}
