package kr.iotdoor.boot.mapper;

import kr.iotdoor.boot.model.file.StoredFile;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface AtchFileDetailMapper {

    @Insert("""
        INSERT INTO TN_ATCH_FILE_DTL (
            ATCH_FILE_IDNTF_NO,
            FILE_SN,
            FILE_STRG_PATH_NM,
            FILE_STRG_NM,
            ORGNL_FILE_NM,
            FILE_EXTN_NM,
            FILE_CN,
            FILE_SZ
        ) VALUES (
            #{atchFileIdntfNo},
            #{fileSn},
            #{fileStrgPathNm},
            #{fileStrgNm},
            #{orgnlFileNm},
            #{fileExtnNm},
            #{fileCn},
            #{fileSz}
        )
        """)
    int insertAtchFileDtl(StoredFile storedFile);

    @Select("""
        SELECT COALESCE(MAX(FILE_SN), 0) + 1 AS FILE_SN
        FROM TN_ATCH_FILE_DTL
        WHERE ATCH_FILE_IDNTF_NO = #{atchFileIdntfNo}
        """)
    int selectAtchFileDtlNextSn(@Param("atchFileIdntfNo") String atchFileIdntfNo);

    @Select("""
        SELECT
            ATCH_FILE_IDNTF_NO,
            FILE_SN,
            FILE_STRG_PATH_NM,
            FILE_STRG_NM,
            ORGNL_FILE_NM,
            FILE_EXTN_NM,
            FILE_CN,
            COALESCE(FILE_SZ, 0) AS FILE_SZ
        FROM TN_ATCH_FILE_DTL
        WHERE ATCH_FILE_IDNTF_NO = #{atchFileIdntfNo}
        """)
    List<StoredFile> selectAtchFileDtlList(@Param("atchFileIdntfNo") String atchFileIdntfNo);

    @Select("""
        SELECT
            ATCH_FILE_IDNTF_NO,
            FILE_SN,
            FILE_STRG_PATH_NM,
            FILE_STRG_NM,
            ORGNL_FILE_NM,
            FILE_EXTN_NM,
            FILE_CN,
            COALESCE(FILE_SZ, 0) AS FILE_SZ
        FROM TN_ATCH_FILE_DTL
        WHERE ATCH_FILE_IDNTF_NO = #{atchFileIdntfNo}
          AND FILE_SN = #{fileSn}
        """)
    StoredFile selectAtchFileDtl(@Param("atchFileIdntfNo") String atchFileIdntfNo, @Param("fileSn") int fileSn);

    @Delete("""
        DELETE FROM TN_ATCH_FILE_DTL
        WHERE ATCH_FILE_IDNTF_NO = #{atchFileIdntfNo}
          AND FILE_SN = #{fileSn}
        """)
    int deleteAtchFileDtl(@Param("atchFileIdntfNo") String atchFileIdntfNo, @Param("fileSn") int fileSn);
}
