package com.ycwl.basic.puzzle.controller;

import com.ycwl.basic.puzzle.dto.PuzzleGenerateRequest;
import com.ycwl.basic.puzzle.dto.PuzzleGenerateResponse;
import com.ycwl.basic.puzzle.service.IPuzzleGenerateService;
import com.ycwl.basic.utils.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 拼图生成Controller（C端API）
 *
 * @author Claude
 * @since 2025-01-17
 */
@Slf4j
@RestController
@RequestMapping("/api/puzzle")
@RequiredArgsConstructor
public class PuzzleGenerateController {

    private final IPuzzleGenerateService generateService;

    /**
     * 生成拼图图片
     */
    @PostMapping("/generate")
    public ApiResponse<PuzzleGenerateResponse> generatePuzzle(@RequestBody PuzzleGenerateRequest request) {
        log.info("拼图生成请求: templateCode={}, userId={}, faceId={}",
                request.getTemplateCode(), request.getUserId(), request.getFaceId());

        // 参数校验
        if (request.getTemplateCode() == null || request.getTemplateCode().trim().isEmpty()) {
            return ApiResponse.fail("模板编码不能为空");
        }

        try {
            PuzzleGenerateResponse response = generateService.generate(request);
            return ApiResponse.success(response);
        } catch (IllegalArgumentException e) {
            log.warn("拼图生成参数错误: {}", e.getMessage());
            return ApiResponse.fail(e.getMessage());
        } catch (Exception e) {
            log.error("拼图生成失败：{}", e.getMessage());
            return ApiResponse.fail("图片生成失败，请稍后重试");
        }
    }
}
