package com.ycwl.basic.controller.pc;

import com.ycwl.basic.dto.RenderWorkerWithStatusDTO;
import com.ycwl.basic.integration.common.response.PageResponse;
import com.ycwl.basic.integration.render.dto.worker.CreateRenderWorkerRequest;
import com.ycwl.basic.integration.render.dto.worker.RenderWorkerV2DTO;
import com.ycwl.basic.integration.render.dto.worker.UpdateRenderWorkerRequest;
import com.ycwl.basic.integration.render.service.RenderWorkerIntegrationService;
import com.ycwl.basic.model.task.req.ClientStatusReqVo;
import com.ycwl.basic.repository.RenderWorkerRepository;
import com.ycwl.basic.utils.ApiResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 渲染工作器管理 V2 版本控制器
 * 基于 zt-render-worker 微服务标准接口实现
 * 
 * @author Claude Code
 * @date 2025-09-06
 */
@Slf4j
@RestController
@RequestMapping("/api/render/worker/v2")
@RequiredArgsConstructor
public class RenderWorkerV2Controller {

    private final RenderWorkerIntegrationService renderWorkerIntegrationService;
    private final RenderWorkerRepository renderWorkerRepository;

    /**
     * 分页查询渲染工作器列表（带保活信息）
     *
     * @param page 页码，从1开始
     * @param pageSize 每页大小，默认10，最大100
     * @param isEnabled 是否启用（0-禁用，1-启用）
     * @param name 工作器名称（模糊搜索）
     * @return 分页查询结果（包含保活信息）
     */
    @GetMapping
    public ApiResponse<PageResponse<RenderWorkerWithStatusDTO>> listWorkers(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Integer isEnabled,
            @RequestParam(required = false) String name) {

        log.debug("分页查询渲染工作器列表, page: {}, pageSize: {}, isEnabled: {}, name: {}",
                page, pageSize, isEnabled, name);

        // 参数验证：限制pageSize最大值为100
        if (pageSize > 100) {
            pageSize = 100;
        }

        try {
            // 获取基础工作器列表
            PageResponse<RenderWorkerV2DTO> basicResult = renderWorkerIntegrationService.listWorkers(
                    page, pageSize, isEnabled, name);

            // 转换为带保活信息的DTO列表
            List<RenderWorkerWithStatusDTO> workersWithStatus = new ArrayList<>();
            for (RenderWorkerV2DTO worker : basicResult.getList()) {
                RenderWorkerWithStatusDTO workerWithStatus = new RenderWorkerWithStatusDTO();

                // 复制基础信息
                BeanUtils.copyProperties(worker, workerWithStatus);

                // 查询保活信息
                ClientStatusReqVo hostStatus = renderWorkerRepository.getWorkerHostStatus(worker.getId());
                workerWithStatus.setHostStatus(hostStatus);
                workerWithStatus.setIsOnline(hostStatus != null);

                workersWithStatus.add(workerWithStatus);
            }

            // 构建带保活信息的分页响应
            PageResponse<RenderWorkerWithStatusDTO> result = new PageResponse<>();
            result.setList(workersWithStatus);
            result.setTotal(basicResult.getTotal());
            result.setPage(basicResult.getPage());
            result.setPageSize(basicResult.getPageSize());

            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("分页查询渲染工作器列表失败", e);
            return ApiResponse.fail("分页查询渲染工作器列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取渲染工作器详情
     *
     * @param id 工作器ID
     * @return 工作器详情
     */
    @GetMapping("/{id}")
    public ApiResponse<RenderWorkerV2DTO> getWorker(@PathVariable Long id) {
        log.debug("获取渲染工作器详情, id: {}", id);
        
        try {
            RenderWorkerV2DTO worker = renderWorkerIntegrationService.getWorker(id);
            return ApiResponse.success(worker);
        } catch (Exception e) {
            log.error("获取渲染工作器详情失败, id: {}", id, e);
            return ApiResponse.fail("获取渲染工作器详情失败: " + e.getMessage());
        }
    }

    /**
     * 创建渲染工作器
     *
     * @param request 创建请求
     * @return 创建的工作器信息
     */
    @PostMapping
    public ApiResponse<RenderWorkerV2DTO> createWorker(@Valid @RequestBody CreateRenderWorkerRequest request) {
        log.debug("创建渲染工作器, name: {}, key: {}, isActive: {}",
                request.getName(), request.getKey(), request.getIsActive());
        
        try {
            RenderWorkerV2DTO worker = renderWorkerIntegrationService.createWorker(request);
            return ApiResponse.success(worker);
        } catch (Exception e) {
            log.error("创建渲染工作器失败", e);
            return ApiResponse.fail("创建渲染工作器失败: " + e.getMessage());
        }
    }

    /**
     * 更新渲染工作器
     *
     * @param id 工作器ID
     * @param request 更新请求
     * @return 操作结果
     */
    @PutMapping("/{id}")
    public ApiResponse<Void> updateWorker(@PathVariable Long id, 
                                          @Valid @RequestBody UpdateRenderWorkerRequest request) {
        log.debug("更新渲染工作器, id: {}, name: {}, isActive: {}",
                id, request.getName(), request.getIsActive());
        
        try {
            renderWorkerIntegrationService.updateWorker(id, request);
            return ApiResponse.success(null);
        } catch (Exception e) {
            log.error("更新渲染工作器失败, id: {}", id, e);
            return ApiResponse.fail("更新渲染工作器失败: " + e.getMessage());
        }
    }

    /**
     * 删除渲染工作器
     *
     * @param id 工作器ID
     * @return 操作结果
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteWorker(@PathVariable Long id) {
        log.debug("删除渲染工作器, id: {}", id);
        
        try {
            renderWorkerIntegrationService.deleteWorker(id);
            return ApiResponse.success(null);
        } catch (Exception e) {
            log.error("删除渲染工作器失败, id: {}", id, e);
            return ApiResponse.fail("删除渲染工作器失败: " + e.getMessage());
        }
    }
}