package com.agileboot.codegen.controller;

import com.agileboot.codegen.dto.CodegenRequest;
import com.agileboot.codegen.service.IGeneratorService;
import com.agileboot.codegen.service.ITemplateRepositoryService;
import com.agileboot.codegen.service.ITemplateUsageLogService;
import com.agileboot.common.core.core.R;
import com.agileboot.common.satoken.utils.LoginHelper;
import com.agileboot.common.core.utils.ServletHolderUtil;
import com.alibaba.fastjson2.JSONArray;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author cuiJiaWang
 * @Create 2025-09-24 14:24
 */
@RestController
@RequestMapping("/codegen")
@Slf4j
@RequiredArgsConstructor
public class GeneratorController {

    private final IGeneratorService generatorService;
    private final ITemplateRepositoryService templateRepositoryService;
    private final ITemplateUsageLogService templateUsageLogService;

    @GetMapping("/template/all")
    public R<?> getAllTemplates() {
        try {
            Long userId = LoginHelper.getUserId();
            JSONArray templates = templateRepositoryService.getUserTemplateConfig(userId);
            return R.ok(templates);
        } catch (Exception e) {
            log.warn("获取用户模板配置失败，使用系统默认配置", e);
            // 降级到系统默认模板
            String templates = generatorService.getTemplateConfig();
            JSONArray jsonArray = JSONArray.parseArray(templates);
            return R.ok(jsonArray);
        }
    }

    @PostMapping("/code/generate")
    public R<?> generateCode(@RequestBody CodegenRequest request) {
        try {
            log.info("开始生成代码，表SQL: {}", request.getTableSql());

            // 合并请求参数
            Map<String, Object> options = new HashMap<>();
            if (request.getOptions() != null) {
                options.putAll(request.getOptions());
            }
            options.put("tableSql", request.getTableSql());

            // 获取用户的模板配置
            Long userId = LoginHelper.getUserId();
            JSONArray userTemplateConfig = templateRepositoryService.getUserTemplateConfig(userId);
            
            // 调用服务生成代码
            Map<String, String> result = generatorService.getResultByParams(options, userTemplateConfig.toJSONString());

            // 检查是否有错误
            if (result.containsKey("error")) {
                return R.fail(result.get("error"));
            }

            // 记录模板使用日志
            try {
                String ipAddress = ServletHolderUtil.getClientIp();
                
                // 从请求参数中获取使用的模板信息
                if (options.containsKey("selectedTemplates")) {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> selectedTemplates = (Map<String, Object>) options.get("selectedTemplates");
                    for (Map.Entry<String, Object> entry : selectedTemplates.entrySet()) {
                        String templateId = entry.getKey();
                        String templateName = entry.getValue().toString();
                        
                        // 判断模板来源
                        String templateSource = templateId.matches("\\d+") ? "system" : "user";
                        
                        templateUsageLogService.logTemplateUsage(userId, templateSource, templateId, 
                                templateName, "unknown", ipAddress);
                    }
                }
            } catch (Exception e) {
                log.warn("记录模板使用日志失败", e);
            }

            Map<String, Object> response = new HashMap<>();
            response.put("outputJson", result);
            response.put("tableName", result.get("tableName"));

            log.info("代码生成完成，表名: {}", result.get("tableName"));
            return R.ok(response);

        } catch (Exception e) {
            log.error("生成代码失败", e);
            return R.fail("生成代码失败: " + e.getMessage());
        }
    }
}
