/*
**************************************************************************************
* Program Name  : AssetStatusChangeRepository.java
* Author        : Kawade Swapnali
* Date          : 2026
* System Name   : gswbs
* Purpose       : Repository interface for Asset Status Change module.
**************************************************************************************
*/

package com.coder.asset.status.change.repository;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

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 org.springframework.stereotype.Repository;

import com.coder.asset.status.change.model.AssetStatusChange;

@Repository
public interface AssetStatusChangeRepository extends JpaRepository<AssetStatusChange, String> {

    /* ================= FETCH SINGLE ================= */
    Optional<AssetStatusChange> findByStatusChangeIdAndCreatedBy(
            String statusChangeId,
            String createdBy
    );

    /* ================= AUTO ID ================= */
    @Query("""
        SELECT s.statusChangeId
        FROM AssetStatusChange s
        WHERE s.statusChangeId LIKE CONCAT(:prefix, '%')
        ORDER BY s.statusChangeId DESC
    """)
    List<String> findTopByPrefix(
            @Param("prefix") String prefix,
            Pageable pageable
    );

    /* ================= FETCH ALL BY CREATED BY ================= */
    List<AssetStatusChange> findAllByCreatedBy(String createdBy);

    /* ================= DUPLICATE CHECK ================= */
    @Query("""
        SELECT s FROM AssetStatusChange s
        WHERE s.assetId = :assetId
        AND s.assetSerialNumber = :assetSerialNumber
        AND s.changeDate = :changeDate
        AND s.createdBy = :createdBy
    """)
    Optional<AssetStatusChange> checkDuplicateRecords(
            @Param("assetId") String assetId,
            @Param("assetSerialNumber") String assetSerialNumber,
            @Param("changeDate") LocalDate changeDate,
            @Param("createdBy") String createdBy
    );
}