package com.zioinfo.kintex.document;

import com.zioinfo.kintex.auth.EventAccessGuard;
import com.zioinfo.kintex.auth.KintexPrincipal;
import com.zioinfo.kintex.common.ApiResponse;
import com.zioinfo.kintex.document.dto.DocumentReviewDto;
import com.zioinfo.kintex.document.dto.DocumentTransitionRequest;
import com.zioinfo.kintex.document.dto.GeneratedDocDto;
import com.zioinfo.kintex.document.dto.MilestoneDto;
import com.zioinfo.kintex.document.dto.ReportPdfRequest;
import com.zioinfo.kintex.document.dto.RequiredDocumentDto;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * M6 서류·마일스톤 API (SCR-22/23). 행사 RBAC 가드.
 * PDF 생성/다운로드는 실구현(G-05). HWP 렌더는 스코프 밖(후속) — 엔드포인트 미노출.
 */
@RestController
@RequestMapping("/api/events/{eventId}")
public class DocumentController {

    private final DocumentService service;
    private final DocumentPdfService pdfService;
    private final EventAccessGuard guard;

    public DocumentController(DocumentService service, DocumentPdfService pdfService, EventAccessGuard guard) {
        this.service = service;
        this.pdfService = pdfService;
        this.guard = guard;
    }

    /** GET /milestones — 전시 마일스톤 진행 노드. */
    @GetMapping("/milestones")
    public ApiResponse<List<MilestoneDto>> milestones(@AuthenticationPrincipal KintexPrincipal principal,
                                                      @PathVariable String eventId) {
        guard.requireEventAccess(principal, eventId);
        return ApiResponse.ok(service.getMilestones(eventId));
    }

    /** GET /documents — 신고서류 체크리스트. */
    @GetMapping("/documents")
    public ApiResponse<List<RequiredDocumentDto>> documents(@AuthenticationPrincipal KintexPrincipal principal,
                                                            @PathVariable String eventId) {
        guard.requireEventAccess(principal, eventId);
        return ApiResponse.ok(service.getDocuments(eventId));
    }

    /** GET /documents/review — AI 서류 검수 + 전체 공정률. */
    @GetMapping("/documents/review")
    public ApiResponse<DocumentReviewDto> review(@AuthenticationPrincipal KintexPrincipal principal,
                                                 @PathVariable String eventId) {
        guard.requireEventAccess(principal, eventId);
        return ApiResponse.ok(service.getReview(eventId));
    }

    /** POST /documents/{docType} — 상태 전이(임시저장 save / 제출 submit). */
    @PostMapping("/documents/{docType}")
    public ApiResponse<RequiredDocumentDto> transition(@AuthenticationPrincipal KintexPrincipal principal,
                                                       @PathVariable String eventId,
                                                       @PathVariable String docType,
                                                       @RequestBody(required = false) DocumentTransitionRequest request) {
        guard.requireEventAccess(principal, eventId);
        String action = request == null ? null : request.action();
        return ApiResponse.ok(service.transition(eventId, docType, action));
    }

    // ── PDF 생성/다운로드 (G-05) ──────────────────────────────────────

    /** POST /documents/{docType}/pdf — SCR-23 웹폼 → 안전관리 계획서 PDF 생성(저장) → 다운로드 메타 반환. */
    @PostMapping("/documents/{docType}/pdf")
    public ApiResponse<GeneratedDocDto> generateReportPdf(@AuthenticationPrincipal KintexPrincipal principal,
                                                          @PathVariable String eventId,
                                                          @PathVariable String docType,
                                                          @RequestBody(required = false) ReportPdfRequest form) {
        guard.requireEventAccess(principal, eventId);
        return ApiResponse.ok(pdfService.generateReport(eventId, docType, form));
    }

    /** POST /document-summary/pdf — SCR-22 서류·마일스톤 현황 요약 PDF(서버 저장 데이터로 조립). */
    @PostMapping("/document-summary/pdf")
    public ApiResponse<GeneratedDocDto> generateSummaryPdf(@AuthenticationPrincipal KintexPrincipal principal,
                                                           @PathVariable String eventId) {
        guard.requireEventAccess(principal, eventId);
        return ApiResponse.ok(pdfService.generateSummary(eventId));
    }

    /** GET /documents/files/{fileId} — 생성된 PDF 다운로드(인증 + 행사 가드). 바이트 스트림. */
    @GetMapping("/documents/files/{fileId}")
    public ResponseEntity<byte[]> downloadPdf(@AuthenticationPrincipal KintexPrincipal principal,
                                              @PathVariable String eventId,
                                              @PathVariable String fileId,
                                              @org.springframework.web.bind.annotation.RequestParam(required = false) String name) {
        guard.requireEventAccess(principal, eventId);
        byte[] pdf = pdfService.load(eventId, fileId);
        String downloadName = (name == null || name.isBlank()) ? fileId : name;
        // 한글 파일명은 RFC 5987(filename*=UTF-8'') 로 인코딩 — 스택트레이스/민감정보 미포함.
        ContentDisposition cd = ContentDisposition.attachment()
                .filename(downloadName, StandardCharsets.UTF_8)
                .build();
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, cd.toString())
                .contentType(MediaType.APPLICATION_PDF)
                .body(pdf);
    }
}
