package com.agent.management.controller;

import com.agent.management.common.Result;
import com.agent.management.model.entity.AgentTemplate;
import com.agent.management.service.AgentTemplateService;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 智能体模板管理 API
 *
 * 用于"创建智能体"时的模式选择 + 模板管理页面 CRUD。
 */
@Slf4j
@RestController
@RequestMapping("/api/agent-templates")
@RequiredArgsConstructor
public class AgentTemplateController {

    private final AgentTemplateService templateService;

    /** 列表（管理端：返回全部，含禁用） */
    @GetMapping
    public Result<List<AgentTemplate>> list(@RequestParam(required = false, defaultValue = "false") boolean enabledOnly) {
        return Result.success(enabledOnly
                ? templateService.listEnabled()
                : templateService.listAll());
    }

    @GetMapping("/{id}")
    public Result<AgentTemplate> get(@PathVariable Long id) {
        return Result.success(templateService.getById(id));
    }

    @PostMapping
    public Result<AgentTemplate> create(@RequestBody AgentTemplateReq req) {
        AgentTemplate tpl = new AgentTemplate();
        tpl.setName(req.getName());
        tpl.setDescription(req.getDescription());
        tpl.setMode(req.getMode());
        tpl.setGraphData(req.getGraphData());
        tpl.setIcon(req.getIcon());
        tpl.setSortOrder(req.getSortOrder());
        tpl.setEnabled(req.getEnabled());
        return Result.success(templateService.create(tpl));
    }

    @PutMapping("/{id}")
    public Result<AgentTemplate> update(@PathVariable Long id, @RequestBody AgentTemplateReq req) {
        AgentTemplate tpl = new AgentTemplate();
        tpl.setName(req.getName());
        tpl.setDescription(req.getDescription());
        tpl.setMode(req.getMode());
        tpl.setGraphData(req.getGraphData());
        tpl.setIcon(req.getIcon());
        tpl.setSortOrder(req.getSortOrder());
        tpl.setEnabled(req.getEnabled());
        return Result.success(templateService.update(id, tpl));
    }

    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        templateService.delete(id);
        return Result.success(null);
    }

    @Data
    public static class AgentTemplateReq {
        private String name;
        private String description;
        private String mode;
        private String graphData;
        private String icon;
        private Integer sortOrder;
        private Boolean enabled;
    }
}
