package com.lingyue.extract.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lingyue.common.domain.AjaxResult;
import com.lingyue.extract.dto.request.CreateProjectRequest;
import com.lingyue.extract.dto.request.UpdateProjectRequest;
import com.lingyue.extract.dto.response.ProjectDetailResponse;
import com.lingyue.extract.dto.response.ProjectListResponse;
import com.lingyue.extract.entity.Project;
import com.lingyue.extract.service.ProjectService;
import com.lingyue.extract.service.SourceDocumentService;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 项目管理控制器
 * 
 * @author lingyue
 * @since 2026-01-22
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/extract/projects")
@RequiredArgsConstructor
@Tag(name = "项目管理", description = "数据提取项目的 CRUD 操作")
public class ProjectController {
    
    private final ProjectService projectService;
    private final SourceDocumentService sourceDocumentService;
    
    @PostMapping
    @Operation(summary = "创建项目")
    public AjaxResult<ProjectDetailResponse> create(
            @RequestHeader(value = "X-User-Id", required = false, defaultValue = "anonymous") String userId,
            @Valid @RequestBody CreateProjectRequest request) {
        
        Project project = projectService.create(userId, request);
        ProjectDetailResponse response = ProjectDetailResponse.fromEntity(project);
        response.setDocumentCount(0);
        response.setRuleCount(0);
        response.setCompletedRuleCount(0);
        
        return AjaxResult.success("创建项目成功", response);
    }
    
    @GetMapping("/{id}")
    @Operation(summary = "获取项目详情")
    public AjaxResult<?> getById(
            @Parameter(description = "项目ID") @PathVariable String id,
            @Parameter(description = "是否包含来源文档列表") @RequestParam(defaultValue = "false") boolean includeDocuments) {
        
        ProjectDetailResponse response;
        if (includeDocuments) {
            response = projectService.getProjectWithDocuments(id, sourceDocumentService);
        } else {
            response = projectService.getProjectDetail(id);
        }
        
        if (response == null) {
            return AjaxResult.error("项目不存在");
        }
        
        return AjaxResult.success(response);
    }
    
    @GetMapping
    @Operation(summary = "分页查询项目列表")
    public AjaxResult<Page<ProjectListResponse>> list(
            @RequestHeader(value = "X-User-Id", required = false, defaultValue = "anonymous") String userId,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") int pageNum,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") int pageSize) {
        
        Page<ProjectListResponse> page = projectService.listByUserId(userId, pageNum, pageSize);
        return AjaxResult.success(page);
    }
    
    @GetMapping("/by-status/{status}")
    @Operation(summary = "按状态查询项目列表")
    public AjaxResult<List<ProjectListResponse>> listByStatus(
            @RequestHeader(value = "X-User-Id", required = false, defaultValue = "anonymous") String userId,
            @Parameter(description = "状态: draft/extracting/completed/archived") @PathVariable String status) {
        
        List<ProjectListResponse> list = projectService.listByUserIdAndStatus(userId, status);
        return AjaxResult.success(list);
    }
    
    @PutMapping("/{id}")
    @Operation(summary = "更新项目")
    public AjaxResult<?> update(
            @RequestHeader(value = "X-User-Id", required = false, defaultValue = "anonymous") String userId,
            @Parameter(description = "项目ID") @PathVariable String id,
            @Valid @RequestBody UpdateProjectRequest request) {
        
        // 权限检查
        if (!projectService.hasAccess(id, userId)) {
            return AjaxResult.error("无权访问该项目");
        }
        
        Project project = projectService.update(id, request, userId);
        if (project == null) {
            return AjaxResult.error("项目不存在");
        }
        
        ProjectDetailResponse response = projectService.getProjectDetail(id);
        return AjaxResult.success("更新项目成功", response);
    }
    
    @DeleteMapping("/{id}")
    @Operation(summary = "删除项目")
    public AjaxResult<?> delete(
            @RequestHeader(value = "X-User-Id", required = false, defaultValue = "anonymous") String userId,
            @Parameter(description = "项目ID") @PathVariable String id) {
        
        // 权限检查
        if (!projectService.hasAccess(id, userId)) {
            return AjaxResult.error("无权访问该项目");
        }
        
        boolean success = projectService.delete(id);
        if (!success) {
            return AjaxResult.error("项目不存在");
        }
        
        return AjaxResult.success("删除项目成功");
    }
    
    @PostMapping("/{id}/archive")
    @Operation(summary = "归档项目")
    public AjaxResult<?> archive(
            @RequestHeader(value = "X-User-Id", required = false, defaultValue = "anonymous") String userId,
            @Parameter(description = "项目ID") @PathVariable String id) {
        
        // 权限检查
        if (!projectService.hasAccess(id, userId)) {
            return AjaxResult.error("无权访问该项目");
        }
        
        Project project = projectService.archive(id, userId);
        if (project == null) {
            return AjaxResult.error("项目不存在");
        }
        
        ProjectDetailResponse response = projectService.getProjectDetail(id);
        return AjaxResult.success("归档项目成功", response);
    }
    
    @GetMapping("/statistics")
    @Operation(summary = "获取用户项目统计")
    public AjaxResult<Map<String, Integer>> getStatistics(
            @RequestHeader(value = "X-User-Id", required = false, defaultValue = "anonymous") String userId) {
        
        Map<String, Integer> statistics = projectService.getProjectStatistics(userId);
        return AjaxResult.success(statistics);
    }
}
