package com.ycwl.basic.controller.mobile;

import com.ycwl.basic.model.jwt.JwtInfo;
import com.ycwl.basic.model.mobile.face.FaceRecognizeResp;
import com.ycwl.basic.model.mobile.goods.GoodsDetailVO;
import com.ycwl.basic.service.mobile.AppAiCamService;
import com.ycwl.basic.utils.ApiResponse;
import com.ycwl.basic.utils.JwtTokenUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * AI相机相关接口
 */
@Slf4j
@RestController
@RequestMapping("/api/mobile/ai_cam/v1")
@RequiredArgsConstructor
public class AppAiCamController {

    private final AppAiCamService appAiCamService;

    /**
     * 根据faceId获取AI相机识别到的商品列表
     * @param faceId 人脸ID
     * @return 商品详情列表
     */
    @GetMapping("/{faceId}/content")
    public ApiResponse<List<GoodsDetailVO>> getAiCamGoods(@PathVariable Long faceId) {
        try {
            List<GoodsDetailVO> goods = appAiCamService.getAiCamGoodsByFaceId(faceId);
            return ApiResponse.success(goods);
        } catch (Exception e) {
            log.error("获取AI相机商品失败: faceId={}", faceId, e);
            return ApiResponse.fail("获取商品列表失败");
        }
    }

    /**
     * 批量添加会员与source的关联关系
     * @param faceId 人脸ID
     * @param sourceIds source ID列表
     * @return 添加结果
     */
    @PostMapping("/{faceId}/relations")
    public ApiResponse<String> addMemberSourceRelations(
        @PathVariable Long faceId,
        @RequestBody List<Long> sourceIds
    ) {
        try {
            int count = appAiCamService.addMemberSourceRelations(faceId, sourceIds);
            return ApiResponse.success("成功添加" + count + "条关联记录");
        } catch (IllegalArgumentException e) {
            log.warn("添加关联失败: faceId={}, error={}", faceId, e.getMessage());
            return ApiResponse.fail(e.getMessage());
        } catch (Exception e) {
            log.error("添加关联失败: faceId={}", faceId, e);
            return ApiResponse.fail("添加关联失败");
        }
    }

    /**
     * 使用人脸样本创建或获取Face记录
     * @param faceSampleId 人脸样本ID
     * @return 人脸识别响应
     */
    @GetMapping("/useSample/{faceSampleId}")
    public ApiResponse<FaceRecognizeResp> useSample(@PathVariable Long faceSampleId) {
        try {
            JwtInfo worker = JwtTokenUtil.getWorker();
            FaceRecognizeResp resp = appAiCamService.useSample(worker.getUserId(), faceSampleId);
            return ApiResponse.success(resp);
        } catch (Exception e) {
            log.error("使用人脸样本失败: faceSampleId={}", faceSampleId, e);
            return ApiResponse.fail("使用人脸样本失败: " + e.getMessage());
        }
    }
}
