package br.gov.sigefp.api;

import br.gov.sigefp.budget.api.dto.BudgetExecutionDTO;
import br.gov.sigefp.budget.service.BudgetExecutionService;
import br.gov.sigefp.common.service.ReportService;
import br.gov.sigefp.rh.api.dto.PayrollRunDTO;
import br.gov.sigefp.rh.service.PayrollService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/reports")
@RequiredArgsConstructor
@Tag(name = "Reports", description = "Endpoints para geração de relatórios e exportação")
public class ReportController {

    private final ReportService reportService;
    private final PayrollService payrollService;
    private final BudgetExecutionService budgetExecutionService;

    @Operation(summary = "Exportar Execução de Folha - Resumo por Funcionário")
    @GetMapping("/payroll/runs/{id}/export")
    public ResponseEntity<byte[]> exportPayrollRun(@PathVariable("id") UUID id,
            @RequestParam(defaultValue = "xlsx") String format) {
        PayrollRunDTO runDTO = payrollService.findPayrollRunById(id);

        // Gerar dados detalhados (uma linha por funcionário, colunas dinâmicas)
        var summaries = payrollService.getPayrollDetailedSummary(id);
        var headers = payrollService.getPayrollDetailedHeaders(id);

        // Gerar título com período formatado
        String periodTitle = runDTO.getPeriodId() != null
                ? "Período: " + runDTO.getPeriodId()
                : "Folha de Pagamento";

        byte[] content;
        String filename = "folha_pagamento_" + runDTO.getPeriodId() + "." + format;
        String contentType;

        if ("pdf".equalsIgnoreCase(format)) {
            content = reportService.generatePdf(summaries, headers,
                    "FOLHA DE PAGAMENTO - " + periodTitle);
            contentType = MediaType.APPLICATION_PDF_VALUE;
        } else {
            content = reportService.generateExcel(summaries, headers, "Folha de Pagamento");
            contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        }

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename)
                .contentType(MediaType.parseMediaType(contentType))
                .body(content);
    }

    @Operation(summary = "Exportar Execução Orçamentária")
    @GetMapping("/budget/execution/export")
    public ResponseEntity<byte[]> exportBudgetExecution(@RequestParam(defaultValue = "xlsx") String format) {
        // Fetch specific page or full list? For export, usually full list. Assuming
        // unpaged support or large page.
        // Using unpaged for now.
        var executions = budgetExecutionService.findAll(Pageable.unpaged()).getContent();

        // Define Headers
        Map<String, String> headers = new LinkedHashMap<>();
        headers.put("budgetLineCode", "Rubrica");
        headers.put("description", "Descrição");
        headers.put("movementType", "Tipo");
        headers.put("amount", "Valor");
        headers.put("createdAt", "Data");

        byte[] content;
        String filename = "budget_execution." + format;
        String contentType;

        if ("pdf".equalsIgnoreCase(format)) {
            content = reportService.generatePdf(executions, headers, "Relatório de Execução Orçamentária");
            contentType = MediaType.APPLICATION_PDF_VALUE;
        } else {
            content = reportService.generateExcel(executions, headers, "Execution");
            contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        }

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename)
                .contentType(MediaType.parseMediaType(contentType))
                .body(content);
    }
}
