package org.xyzh.ai.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.xyzh.api.ai.service.AgentService;
import org.xyzh.api.ai.dto.TbAgent;
import org.xyzh.common.core.domain.ResultDomain;
import org.xyzh.common.core.page.PageRequest;
import org.xyzh.common.utils.validation.ValidationResult;
import org.xyzh.common.utils.validation.ValidationParam;
import org.xyzh.common.utils.validation.ValidationUtils;

import jakarta.validation.constraints.NotNull;

import java.util.Arrays;

/**
 * @description 智能体控制器
 * @filename AgentController.java
 * @author yslg
 * @copyright xyzh
 * @since 2025-12-17
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/ai/agent")
public class AgentController {

    @Autowired
    private AgentService agentService;

    /**
     * @description    创建智能体
     * @param    agent
     * @author    yslg
     * @since 2025-12-17
     */
    @PostMapping
    @PreAuthorize("hasAuthority('ai:agent:create')")
    public ResultDomain<TbAgent> createAgent(@RequestBody TbAgent agent) {
        log.info("创建智能体: name={}", agent.getName());
        // 参数校验
        ValidationResult result = ValidationUtils.validate(agent, Arrays.asList(
                    ValidationUtils.requiredString("name", "智能体名称", 1, 100),
                    ValidationUtils.requiredString("apiKey", "API密钥", 1, 100),
                    ValidationUtils.requiredString("link", "智能体url",10,500)
                ));
        if (!result.isValid()) {
            return ResultDomain.failure(result.getAllErrors());
        }
        return agentService.addAgent(agent);
    }

    /**
     * @description    更新智能体
     * @param    agent
     * @author    yslg
     * @since 2025-12-17
     */
    @PutMapping
    @PreAuthorize("hasAuthority('ai:agent:update')")
    public ResultDomain<TbAgent> updateAgent(@RequestBody TbAgent agent) {
        log.info("更新智能体: agentId={}", agent.getAgentId());
        // 参数校验
        ValidationResult result = ValidationUtils.validate(agent, Arrays.asList(
                ValidationUtils.requiredString("agentId", "智能体ID"),
                ValidationUtils.requiredString("name", "智能体名称", 1, 100),
                ValidationUtils.requiredString("apiKey", "API密钥", 1, 100),
                ValidationUtils.requiredString("link", "智能体url",10,500)
        ));
        if (!result.isValid()) {
            return ResultDomain.failure(result.getAllErrors());
        }
        return agentService.updateAgent(agent);
    }

    /**
     * @description    删除智能体
     * @param    agentId
     * @author    yslg
     * @since 2025-12-17
     */
    @DeleteMapping("/{agentId}")
    @PreAuthorize("hasAuthority('ai:agent:delete')")
    public ResultDomain<TbAgent> deleteAgent(@PathVariable("agentId") @NotNull String agentId) {
        log.info("删除智能体: agentId={}", agentId);
        TbAgent agent = new TbAgent();
        agent.setAgentId(agentId);
        return agentService.deleteAgent(agent);
    }

    /**
     * @description    获取智能体详情
     * @param    agentId
     * @author    yslg
     * @since 2025-12-17
     */
    @GetMapping("/{agentId}")
    @PreAuthorize("hasAuthority('ai:agent:view')")
    public ResultDomain<TbAgent> getAgent(@PathVariable("agentId") @NotNull String agentId) {
        log.info("获取智能体: agentId={}", agentId);
        ResultDomain<TbAgent> agentResult = agentService.selectAgentById(agentId);
        if (agentResult.getSuccess() && agentResult.getData() != null) {
            return ResultDomain.success("查询成功", agentResult.getData());
        }
        return ResultDomain.failure("智能体不存在"+agentResult.getMessage());
    }

    /**
     * @description    分页查询智能体
     * @param    pageRequest
     * @author    yslg
     * @since 2025-12-17
     */
    @PostMapping("/page")
    @PreAuthorize("hasAuthority('ai:agent:view')")
    public ResultDomain<TbAgent> getAgentPage(@RequestBody PageRequest<TbAgent> pageRequest) {
        log.info("分页查询智能体");
        // 参数校验（支持嵌套属性路径）
        ValidationResult result = ValidationUtils.validate(pageRequest, Arrays.asList(
                ValidationParam.builder().fieldName("pageParam").fieldLabel("分页参数").required().build(),
                ValidationUtils.requiredNumber("pageParam.page", "页码", 1, null),
                ValidationUtils.requiredNumber("pageParam.pageSize", "每页条数", 1, 100)
        ));
        if (!result.isValid()) {
            return ResultDomain.failure(result.getAllErrors());
        }
        return agentService.getAgentPage(pageRequest);
    }

    /**
     * @description    获取智能体列表
     * @param    tbAgent
     * @author    yslg
     * @since 2025-12-17
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('ai:agent:view')")
    public ResultDomain<TbAgent> getAgentList(TbAgent tbAgent) {
        log.info("获取智能体列表");
        return agentService.getAgentList(tbAgent);
    }
}
