package com.yaoai.domain.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yaoai.domain.entity.ShotAsset;
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;

@Mapper
public interface ShotAssetMapper extends BaseMapper<ShotAsset> {

    @Select("SELECT * FROM shot_assets WHERE storyboard_id=#{storyboardId} AND is_active=1 ORDER BY created_at DESC")
    List<ShotAsset> findActiveByStoryboard(Long storyboardId);

    @Select("SELECT * FROM shot_assets WHERE storyboard_id=#{storyboardId} AND tenant_id=#{tenantId} ORDER BY asset_type, asset_version DESC, created_at DESC")
    List<ShotAsset> findByStoryboard(@Param("storyboardId") Long storyboardId, @Param("tenantId") Long tenantId);

    @Select("SELECT * FROM shot_assets WHERE storyboard_id=#{storyboardId} AND tenant_id=#{tenantId} AND asset_type=#{assetType} ORDER BY asset_version DESC, created_at DESC")
    List<ShotAsset> findHistory(@Param("storyboardId") Long storyboardId,
                                @Param("tenantId") Long tenantId,
                                @Param("assetType") String assetType);

    @Select("SELECT COALESCE(MAX(asset_version), 0) FROM shot_assets WHERE storyboard_id=#{storyboardId} AND tenant_id=#{tenantId} AND asset_type=#{assetType}")
    Integer maxVersion(@Param("storyboardId") Long storyboardId,
                       @Param("tenantId") Long tenantId,
                       @Param("assetType") String assetType);

    @Select("SELECT * FROM shot_assets WHERE source_task_id=#{sourceTaskId} AND tenant_id=#{tenantId} LIMIT 1")
    ShotAsset findBySourceTask(@Param("sourceTaskId") Long sourceTaskId, @Param("tenantId") Long tenantId);

    @Update("UPDATE shot_assets SET is_active=0 WHERE storyboard_id=#{storyboardId} AND tenant_id=#{tenantId} AND asset_type=#{assetType} AND is_active=1")
    int deactivateActive(@Param("storyboardId") Long storyboardId,
                         @Param("tenantId") Long tenantId,
                         @Param("assetType") String assetType);
}
