package com.lingyue.extract.controller;

import com.lingyue.common.domain.AjaxResult;
import com.lingyue.extract.dto.request.AddSourceDocumentRequest;
import com.lingyue.extract.dto.request.BatchAddSourceDocumentsRequest;
import com.lingyue.extract.dto.request.ReorderSourceDocumentsRequest;
import com.lingyue.extract.dto.request.UpdateSourceDocumentRequest;
import com.lingyue.extract.dto.response.SourceDocumentResponse;
import com.lingyue.extract.entity.SourceDocument;
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.stream.Collectors;

/**
 * 来源文档管理控制器
 * 
 * @author lingyue
 * @since 2026-01-22
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/extract/projects/{projectId}/documents")
@RequiredArgsConstructor
@Tag(name = "来源文档管理", description = "项目来源文档的 CRUD 操作")
public class SourceDocumentController {
    
    private final SourceDocumentService sourceDocumentService;
    private final ProjectService projectService;
    
    @PostMapping
    @Operation(summary = "添加来源文档")
    public AjaxResult<?> add(
            @RequestHeader(value = "X-User-Id", required = false, defaultValue = "anonymous") String userId,
            @Parameter(description = "项目ID") @PathVariable String projectId,
            @Valid @RequestBody AddSourceDocumentRequest request) {
        
        // 权限检查
        if (!projectService.hasAccess(projectId, userId)) {
            return AjaxResult.error("无权访问该项目");
        }
        
        SourceDocument doc = sourceDocumentService.add(projectId, request);
        SourceDocumentResponse response = SourceDocumentResponse.fromEntity(doc);
        
        return AjaxResult.success("添加来源文档成功", response);
    }
    
    @PostMapping("/batch")
    @Operation(summary = "批量添加来源文档")
    public AjaxResult<?> batchAdd(
            @RequestHeader(value = "X-User-Id", required = false, defaultValue = "anonymous") String userId,
            @Parameter(description = "项目ID") @PathVariable String projectId,
            @Valid @RequestBody BatchAddSourceDocumentsRequest request) {
        
        // 权限检查
        if (!projectService.hasAccess(projectId, userId)) {
            return AjaxResult.error("无权访问该项目");
        }
        
        List<SourceDocument> docs = sourceDocumentService.batchAdd(projectId, request);
        List<SourceDocumentResponse> responses = docs.stream()
                .map(SourceDocumentResponse::fromEntity)
                .collect(Collectors.toList());
        
        return AjaxResult.success("批量添加来源文档成功", responses);
    }
    
    @GetMapping
    @Operation(summary = "获取项目的来源文档列表")
    public AjaxResult<List<SourceDocumentResponse>> list(
            @Parameter(description = "项目ID") @PathVariable String projectId) {
        
        List<SourceDocumentResponse> list = sourceDocumentService.listByProjectId(projectId);
        return AjaxResult.success(list);
    }
    
    @GetMapping("/{id}")
    @Operation(summary = "获取来源文档详情")
    public AjaxResult<?> getById(
            @Parameter(description = "项目ID") @PathVariable String projectId,
            @Parameter(description = "来源文档ID") @PathVariable String id) {
        
        SourceDocumentResponse response = sourceDocumentService.getSourceDocumentResponse(id);
        if (response == null) {
            return AjaxResult.error("来源文档不存在");
        }
        
        // 验证文档属于该项目
        if (!response.getProjectId().equals(projectId)) {
            return AjaxResult.error("来源文档不属于该项目");
        }
        
        return AjaxResult.success(response);
    }
    
    @PutMapping("/{id}")
    @Operation(summary = "更新来源文档")
    public AjaxResult<?> update(
            @RequestHeader(value = "X-User-Id", required = false, defaultValue = "anonymous") String userId,
            @Parameter(description = "项目ID") @PathVariable String projectId,
            @Parameter(description = "来源文档ID") @PathVariable String id,
            @Valid @RequestBody UpdateSourceDocumentRequest request) {
        
        // 权限检查
        if (!projectService.hasAccess(projectId, userId)) {
            return AjaxResult.error("无权访问该项目");
        }
        
        // 验证文档属于该项目
        SourceDocument existing = sourceDocumentService.getById(id);
        if (existing == null) {
            return AjaxResult.error("来源文档不存在");
        }
        if (!existing.getProjectId().equals(projectId)) {
            return AjaxResult.error("来源文档不属于该项目");
        }
        
        SourceDocument doc = sourceDocumentService.update(id, request);
        SourceDocumentResponse response = SourceDocumentResponse.fromEntity(doc);
        
        return AjaxResult.success("更新来源文档成功", response);
    }
    
    @DeleteMapping("/{id}")
    @Operation(summary = "移除来源文档")
    public AjaxResult<?> remove(
            @RequestHeader(value = "X-User-Id", required = false, defaultValue = "anonymous") String userId,
            @Parameter(description = "项目ID") @PathVariable String projectId,
            @Parameter(description = "来源文档ID") @PathVariable String id,
            @Parameter(description = "是否强制删除（同时删除关联规则）") @RequestParam(defaultValue = "false") boolean force) {
        
        // 权限检查
        if (!projectService.hasAccess(projectId, userId)) {
            return AjaxResult.error("无权访问该项目");
        }
        
        // 验证文档属于该项目
        SourceDocument existing = sourceDocumentService.getById(id);
        if (existing == null) {
            return AjaxResult.error("来源文档不存在");
        }
        if (!existing.getProjectId().equals(projectId)) {
            return AjaxResult.error("来源文档不属于该项目");
        }
        
        try {
            boolean success;
            if (force) {
                success = sourceDocumentService.forceRemove(id);
            } else {
                success = sourceDocumentService.remove(id);
            }
            
            if (!success) {
                return AjaxResult.error("移除来源文档失败");
            }
            
            return AjaxResult.success("移除来源文档成功");
        } catch (IllegalStateException e) {
            return AjaxResult.error(e.getMessage());
        }
    }
    
    @PostMapping("/reorder")
    @Operation(summary = "调整来源文档顺序")
    public AjaxResult<?> reorder(
            @RequestHeader(value = "X-User-Id", required = false, defaultValue = "anonymous") String userId,
            @Parameter(description = "项目ID") @PathVariable String projectId,
            @Valid @RequestBody ReorderSourceDocumentsRequest request) {
        
        // 权限检查
        if (!projectService.hasAccess(projectId, userId)) {
            return AjaxResult.error("无权访问该项目");
        }
        
        sourceDocumentService.reorder(projectId, request);
        return AjaxResult.success("调整顺序成功");
    }
}
