package com.erp.controller;

import com.erp.dto.ApiResponse;
import com.erp.service.ReportService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.*;

@RestController
@RequestMapping("/api/report")
@RequiredArgsConstructor
@Slf4j
public class ReportController {

    private final ReportService reportService;

    // ── 외부 DB 연결 목록 ─────────────────────────────────────────────────────

    @GetMapping("/external-connections")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getExternalConnections(
            @RequestAttribute("company_code") String companyCode,
            @RequestParam Map<String, Object> params) {
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(reportService.getExternalConnections(params)));
    }

    // ── 템플릿 ────────────────────────────────────────────────────────────────

    @GetMapping("/templates")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getTemplates() {
        return ResponseEntity.ok(ApiResponse.success(reportService.getTemplates()));
    }

    @PostMapping("/templates")
    public ResponseEntity<ApiResponse<Map<String, Object>>> createTemplate(
            @RequestAttribute(value = "user_id", required = false) String userId,
            @RequestBody Map<String, Object> body) {
        body.put("created_by", userId);
        Map<String, Object> result = reportService.createTemplate(body);
        return ResponseEntity.status(201).body(ApiResponse.success(result));
    }

    @PostMapping("/templates/create-from-layout")
    public ResponseEntity<ApiResponse<Map<String, Object>>> createTemplateFromLayout(
            @RequestAttribute(value = "user_id", required = false) String userId,
            @RequestBody Map<String, Object> body) {
        body.put("created_by", userId);
        Map<String, Object> result = reportService.createTemplateFromLayout(body);
        return ResponseEntity.status(201).body(ApiResponse.success(result));
    }

    @DeleteMapping("/templates/{templateId}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> deleteTemplate(
            @PathVariable String templateId) {
        Map<String, Object> params = new HashMap<>();
        params.put("template_id", templateId);
        return ResponseEntity.ok(ApiResponse.success(reportService.deleteTemplate(params)));
    }

    // ── 이미지 업로드 (stub) ──────────────────────────────────────────────────

    @PostMapping("/upload-image")
    public ResponseEntity<ApiResponse<Map<String, Object>>> uploadImage() {
        return ResponseEntity.status(501).body(
            ApiResponse.error("이미지 업로드는 현재 지원되지 않습니다."));
    }

    // ── Word 내보내기 (stub) ──────────────────────────────────────────────────

    @PostMapping("/export-word")
    public ResponseEntity<ApiResponse<Map<String, Object>>> exportToWord() {
        return ResponseEntity.status(501).body(
            ApiResponse.error("Word 내보내기는 현재 지원되지 않습니다."));
    }

    // ── 리포트 목록 ───────────────────────────────────────────────────────────

    @GetMapping
    public ResponseEntity<ApiResponse<Map<String, Object>>> getReportList(
            @RequestAttribute("company_code") String companyCode,
            @RequestParam Map<String, Object> params) {
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(reportService.getReportList(params)));
    }

    // ── 리포트 생성 ───────────────────────────────────────────────────────────

    @PostMapping
    public ResponseEntity<ApiResponse<Map<String, Object>>> createReport(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute(value = "user_id", required = false) String userId,
            @RequestBody Map<String, Object> body) {
        if (body.get("report_name_kor") == null || body.get("report_type") == null) {
            return ResponseEntity.status(400).body(
                ApiResponse.error("리포트명과 리포트 타입은 필수입니다."));
        }
        body.put("company_code", companyCode);
        body.put("created_by", userId);
        Map<String, Object> result = reportService.createReport(body);
        return ResponseEntity.status(201).body(ApiResponse.success(result, "리포트가 생성되었습니다."));
    }

    // ── 리포트 복사 ───────────────────────────────────────────────────────────

    @PostMapping("/{reportId}/copy")
    public ResponseEntity<ApiResponse<Map<String, Object>>> copyReport(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute(value = "user_id", required = false) String userId,
            @PathVariable String reportId) {
        Map<String, Object> params = new HashMap<>();
        params.put("report_id", reportId);
        params.put("company_code", companyCode);
        params.put("user_id", userId);
        Map<String, Object> result = reportService.copyReport(params);
        if (result == null) {
            return ResponseEntity.status(404).body(ApiResponse.error("리포트를 찾을 수 없습니다."));
        }
        return ResponseEntity.status(201).body(ApiResponse.success(result));
    }

    // ── 템플릿으로 저장 ───────────────────────────────────────────────────────

    @PostMapping("/{reportId}/save-as-template")
    public ResponseEntity<ApiResponse<Map<String, Object>>> saveAsTemplate(
            @RequestAttribute(value = "user_id", required = false) String userId,
            @PathVariable String reportId,
            @RequestBody Map<String, Object> body) {
        body.put("report_id", reportId);
        body.put("user_id", userId);
        Map<String, Object> result = reportService.saveAsTemplate(body);
        return ResponseEntity.status(201).body(ApiResponse.success(result));
    }

    // ── 레이아웃 조회/저장 ────────────────────────────────────────────────────

    @GetMapping("/{reportId}/layout")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getLayout(
            @PathVariable String reportId) {
        Map<String, Object> params = Map.of("report_id", reportId);
        Map<String, Object> result = reportService.getLayout(params);
        if (result == null) {
            return ResponseEntity.status(404).body(ApiResponse.error("레이아웃을 찾을 수 없습니다."));
        }
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    @PutMapping("/{reportId}/layout")
    public ResponseEntity<ApiResponse<Map<String, Object>>> saveLayout(
            @RequestAttribute(value = "user_id", required = false) String userId,
            @PathVariable String reportId,
            @RequestBody Map<String, Object> body) {
        body.put("report_id", reportId);
        body.put("user_id", userId);
        Map<String, Object> result = reportService.saveLayout(body);
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    // ── 쿼리 실행 ────────────────────────────────────────────────────────────

    @PostMapping("/{reportId}/queries/{queryId}/execute")
    public ResponseEntity<ApiResponse<Map<String, Object>>> executeQuery(
            @PathVariable String reportId,
            @PathVariable String queryId,
            @RequestBody Map<String, Object> body) {
        body.put("report_id", reportId);
        body.put("query_id", queryId);
        Map<String, Object> result = reportService.executeQuery(body);
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    // ── 리포트 상세 / 수정 / 삭제 ────────────────────────────────────────────

    @GetMapping("/{reportId}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getReportInfo(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String reportId) {
        Map<String, Object> params = new HashMap<>();
        params.put("report_id", reportId);
        params.put("company_code", companyCode);
        Map<String, Object> result = reportService.getReportInfo(params);
        if (result == null) {
            return ResponseEntity.status(404).body(ApiResponse.error("리포트를 찾을 수 없습니다."));
        }
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    @PutMapping("/{reportId}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> updateReport(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute(value = "user_id", required = false) String userId,
            @PathVariable String reportId,
            @RequestBody Map<String, Object> body) {
        body.put("report_id", reportId);
        body.put("company_code", companyCode);
        body.put("updated_by", userId);
        return ResponseEntity.ok(ApiResponse.success(reportService.updateReport(body)));
    }

    @DeleteMapping("/{reportId}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> deleteReport(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String reportId) {
        Map<String, Object> params = new HashMap<>();
        params.put("report_id", reportId);
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(reportService.deleteReport(params)));
    }

    // ── 이전 /list 경로 호환 ──────────────────────────────────────────────────

    @GetMapping("/list")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getReportListLegacy(
            @RequestAttribute("company_code") String companyCode,
            @RequestParam Map<String, Object> params) {
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(reportService.getReportList(params)));
    }
}
