package com.erp.product.sku.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.erp.common.core.model.ApiResponse;
import com.erp.product.sku.dto.*;
import com.erp.product.sku.service.SkuMatchService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * SKU匹配控制器
 * 
 * 功能：SKU匹配列表 / 手动匹配 / 规则匹配 / AI匹配 / 未匹配商品
 */
@Slf4j
@RestController
@RequestMapping("/api/sku-match")
@RequiredArgsConstructor
public class SkuMatchController {
    
    private final SkuMatchService skuMatchService;
    
    /**
     * SKU匹配列表
     */
    @GetMapping("/bindings")
    public ApiResponse<IPage<SkuBindingDTO>> listBindings(SkuMatchPageRequest request) {
        IPage<SkuBindingDTO> page = skuMatchService.listBindings(request);
        return ApiResponse.success(page);
    }
    
    /**
     * 未匹配商品列表
     */
    @GetMapping("/unmatched")
    public ApiResponse<IPage<UnmatchedSkuDTO>> listUnmatched(SkuMatchPageRequest request) {
        IPage<UnmatchedSkuDTO> page = skuMatchService.listUnmatched(request);
        return ApiResponse.success(page);
    }
    
    /**
     * 手动匹配 - 绑定平台SKU到ERP SKU
     */
    @PostMapping("/bind")
    public ApiResponse<SkuBindingDTO> manualBind(@Valid @RequestBody ManualBindRequest request) {
        // 获取租户ID（从header或上下文中）
        Long tenantId = getTenantId();
        SkuBindingDTO result = skuMatchService.manualBind(request, tenantId);
        return ApiResponse.success(result);
    }
    
    /**
     * 规则匹配 - 按规则自动匹配
     */
    @PostMapping("/rule-match")
    public ApiResponse<RuleMatchResponse> ruleMatch(@RequestBody RuleMatchRequest request) {
        Long tenantId = getTenantId();
        RuleMatchResponse result = skuMatchService.ruleMatch(request, tenantId);
        return ApiResponse.success(result);
    }
    
    /**
     * AI匹配 - 发起AI匹配任务
     */
    @PostMapping("/ai-match")
    public ApiResponse<SkuMatchAiTaskResponse> aiMatch(@RequestBody AiMatchRequest request) {
        Long tenantId = getTenantId();
        SkuMatchAiTaskResponse result = skuMatchService.aiMatch(request, tenantId);
        return ApiResponse.success(result);
    }
    
    /**
     * 解绑SKU匹配
     */
    @DeleteMapping("/bindings/{id}")
    public ApiResponse<Void> unbind(@PathVariable("id") Long id) {
        Long tenantId = getTenantId();
        skuMatchService.unbind(id, tenantId);
        return ApiResponse.success(null);
    }
    
    /**
     * 获取当前租户ID（实际应从安全上下文中获取）
     */
    private Long getTenantId() {
        // TODO: 从安全上下文或header中获取租户ID
        return 1L;
    }
}
