package com.rj.mapper;

import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.rj.entity.AudioManagementSegments;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * <p>
 * 录音分段管理表 Mapper 接口
 * </p>
 *
 * 对应表：audio_management_segments
 */
@Mapper
public interface AudioManagementSegmentsMapper extends BaseMapper<AudioManagementSegments> {

    /**
     * 本地路径已填、MinIO URL 未填的分段。使用注解 SQL，避免 Lambda 条件生成 audio_file_url / audio_file_path 的多余占位符，
     * 并在此方法上关闭租户行插件（否则会出现 tenant_id = null 等错误条件）。
     */
    @InterceptorIgnore(tenantLine = "true")
    @Select("SELECT * FROM audio_management_segments WHERE (audio_file_url IS NULL OR audio_file_url = '') "
            + "AND audio_file_path IS NOT NULL AND audio_file_path <> '' "
            + "ORDER BY create_time ASC LIMIT #{limit}")
    List<AudioManagementSegments> listSegmentsNeedingMinioUpload(@Param("limit") int limit);

    /**
     * 仅按主键更新 MinIO URL，不拼接 tenant_id（供调度任务等无租户上下文场景使用）。
     */
    @InterceptorIgnore(tenantLine = "true")
    @Update("UPDATE audio_management_segments SET audio_file_url = #{audioFileUrl} WHERE id = #{id}")
    int updateAudioFileUrlByIdIgnoreTenant(@Param("id") String id, @Param("audioFileUrl") String audioFileUrl);

    /** 依原始音频文件名更新分段转写文本（调度任务等无租户上下文场景）。 */
    @InterceptorIgnore(tenantLine = "true")
    @Update("UPDATE audio_management_segments SET recording_text = #{recordingText} "
            + "WHERE audio_file_original_name = #{audioFileOriginalName}")
    int updateRecordingTextByAudioFileOriginalNameIgnoreTenant(
            @Param("recordingText") String recordingText,
            @Param("audioFileOriginalName") String audioFileOriginalName);

    /** 音频移至完成目录后，按原始文件名回写磁盘路径（与外部 ASR 脚本行为一致）。 */
    @InterceptorIgnore(tenantLine = "true")
    @Update("UPDATE audio_management_segments SET audio_file_path = #{audioFilePath} "
            + "WHERE audio_file_original_name = #{audioFileOriginalName}")
    int updateAudioFilePathByAudioFileOriginalNameIgnoreTenant(
            @Param("audioFilePath") String audioFilePath,
            @Param("audioFileOriginalName") String audioFileOriginalName);

    @InterceptorIgnore(tenantLine = "true")
    @Select("SELECT parent_id FROM audio_management_segments WHERE audio_file_original_name = #{audioFileOriginalName} "
            + "LIMIT 1")
    String selectParentIdByAudioFileOriginalNameLimit1(@Param("audioFileOriginalName") String audioFileOriginalName);

    /** 汇总父录音下各段文本与时长（仅查必要列）。 */
    @InterceptorIgnore(tenantLine = "true")
    @Select("SELECT id, recording_text, duration FROM audio_management_segments WHERE parent_id = #{parentId} "
            + "ORDER BY id ASC")
    List<AudioManagementSegments> listRecordingPartsByParentId(@Param("parentId") String parentId);
}
