package com.erp.product.sku.repository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.product.sku.entity.PlatformSkuBinding;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

/**
 * 平台SKU绑定 Repository
 */
@Mapper
public interface PlatformSkuBindingRepository extends BaseMapper<PlatformSkuBinding> {
    
    /**
     * 查询生效的绑定
     */
    @Select("SELECT * FROM platform_sku_bindings " +
            "WHERE platform_sku_id = #{platformSkuId} AND is_active = true")
    PlatformSkuBinding findActiveByPlatformSkuId(@Param("platformSkuId") Long platformSkuId);
    
    /**
     * 解绑指定平台SKU的所有绑定
     */
    @Update("UPDATE platform_sku_bindings SET is_active = false, unbound_at = NOW() " +
            "WHERE platform_sku_id = #{platformSkuId} AND is_active = true")
    int deactivateByPlatformSkuId(@Param("platformSkuId") Long platformSkuId);
    
    /**
     * 分页查询绑定列表
     */
    @Select("SELECT b.* FROM platform_sku_bindings b " +
            "INNER JOIN platforms p ON b.platform_sku_id = p.id " +
            "INNER JOIN erp_skus e ON b.erp_sku_id = e.id " +
            "WHERE b.is_active = true " +
            "ORDER BY b.updated_at DESC")
    IPage<PlatformSkuBinding> findActiveBindingsPage(Page<PlatformSkuBinding> page);
}
