package org.dromara.ai.controller.app;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.web.core.BaseController;
import org.dromara.ai.domain.bo.AiPaintingTemplateBo;
import org.dromara.ai.domain.vo.AiPaintingTemplateVo;
import org.dromara.ai.service.AiPaintingTemplateService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * 用户端AI绘画参数模板
 *
 * @author pengles
 */
@Tag(name = "用户端-AI绘画参数模板", description = "用户端AI绘画参数模板接口")
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/app/ai/painting/template")
public class AppAiPaintingTemplateController extends BaseController {

    private final AiPaintingTemplateService aiPaintingTemplateService;

    /**
     * 查询可用的模板列表
     */
    @Operation(summary = "查询可用的模板列表", description = "根据引擎类型查询可用的模板列表（公开模板 + 用户私有模板）")
    @GetMapping("/list/{engineType}")
    public R<List<AiPaintingTemplateVo>> getAvailableTemplates(@Parameter(description = "引擎类型", required = true)
                                                                 @PathVariable String engineType) {
        Long userId = null;
        try {
            userId = LoginHelper.getUserId();
        } catch (Exception e) {
            // 未登录用户只能看到公开模板
        }
        List<AiPaintingTemplateVo> list = aiPaintingTemplateService.queryAvailableTemplates(engineType, userId);
        return R.ok(list);
    }

    /**
     * 获取模板详情
     */
    @Operation(summary = "获取模板详情", description = "根据模板ID获取详细信息")
    @GetMapping("/{id}")
    public R<AiPaintingTemplateVo> getInfo(@Parameter(description = "模板ID", required = true)
                                            @PathVariable Long id) {
        return R.ok(aiPaintingTemplateService.queryById(id));
    }

    /**
     * 新增用户私有模板
     */
    @Operation(summary = "新增用户私有模板", description = "新增用户私有绘画参数模板")
    @PostMapping
    public R<Void> add(@Valid @RequestBody AiPaintingTemplateBo bo) {
        // 自动设置用户ID
        Long userId = LoginHelper.getUserId();
        bo.setUserId(userId);
        bo.setIsPublic(0); // 用户创建的模板默认为私有
        return toAjax(aiPaintingTemplateService.insertByBo(bo));
    }

    /**
     * 修改用户私有模板
     */
    @Operation(summary = "修改用户私有模板", description = "修改用户私有绘画参数模板（只能修改自己的模板）")
    @PutMapping
    public R<Void> edit(@Valid @RequestBody AiPaintingTemplateBo bo) {
        // 验证模板所有权
        Long userId = LoginHelper.getUserId();
        AiPaintingTemplateVo existing = aiPaintingTemplateService.queryById(bo.getId());
        if (existing == null || !userId.equals(existing.getUserId())) {
            return R.fail("无权修改该模板");
        }
        bo.setUserId(userId); // 确保用户ID不变
        return toAjax(aiPaintingTemplateService.updateByBo(bo));
    }

    /**
     * 删除用户私有模板
     */
    @Operation(summary = "删除用户私有模板", description = "删除用户私有绘画参数模板（只能删除自己的模板）")
    @DeleteMapping("/{id}")
    public R<Void> remove(@Parameter(description = "模板ID", required = true)
                           @PathVariable Long id) {
        // 验证模板所有权
        Long userId = LoginHelper.getUserId();
        AiPaintingTemplateVo existing = aiPaintingTemplateService.queryById(id);
        if (existing == null || !userId.equals(existing.getUserId())) {
            return R.fail("无权删除该模板");
        }
        return toAjax(aiPaintingTemplateService.deleteWithValidByIds(Arrays.asList(id), true));
    }

}
