package br.gov.sigefp.rh.api;

import br.gov.sigefp.common.exception.BusinessException;
import br.gov.sigefp.rh.api.dto.CreatePayrollPeriodDTO;
import br.gov.sigefp.rh.api.dto.CreatePayrollRunDTO;
import br.gov.sigefp.rh.api.dto.PayrollPeriodDTO;
import br.gov.sigefp.rh.api.dto.PayrollRunDTO;
import br.gov.sigefp.rh.service.PayrollService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;

/**
 * Controller REST para gestão de folha de pagamento.
 */
@RestController
@RequestMapping("/api/rh")
@RequiredArgsConstructor
public class PayrollController {

    private final PayrollService payrollService;

    @GetMapping("/payroll-periods")
    public ResponseEntity<List<PayrollPeriodDTO>> findAllPeriods() {
        List<PayrollPeriodDTO> periods = payrollService.findAllPeriods();
        return ResponseEntity.ok(periods);
    }

    @PostMapping("/payroll-periods")
    public ResponseEntity<PayrollPeriodDTO> createPeriod(@Valid @RequestBody CreatePayrollPeriodDTO dto) {
        try {
            PayrollPeriodDTO created = payrollService.createPeriod(dto);
            return ResponseEntity.status(HttpStatus.CREATED).body(created);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @PutMapping("/payroll-periods/{id}/status")
    public ResponseEntity<PayrollPeriodDTO> updatePeriodStatus(
            @PathVariable UUID id,
            @RequestParam String status) {
        try {
            PayrollPeriodDTO updated = payrollService.updatePeriodStatus(id, status);
            return ResponseEntity.ok(updated);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.notFound().build();
        }
    }

    @GetMapping("/payroll-runs")
    public ResponseEntity<List<PayrollRunDTO>> findAllPayrollRuns() {
        List<PayrollRunDTO> runs = payrollService.findAllPayrollRuns();
        return ResponseEntity.ok(runs);
    }

    @PostMapping("/payroll-runs")
    public ResponseEntity<PayrollRunDTO> createPayrollRun(@Valid @RequestBody CreatePayrollRunDTO dto) {
        try {
            PayrollRunDTO created = payrollService.createPayrollRun(dto);
            return ResponseEntity.status(HttpStatus.CREATED).body(created);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @GetMapping("/payroll-runs/{id}")
    public ResponseEntity<PayrollRunDTO> findPayrollRunById(@PathVariable("id") UUID id) {
        try {
            PayrollRunDTO dto = payrollService.findPayrollRunById(id);
            return ResponseEntity.ok(dto);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * Processa uma execução de folha, criando execuções orçamentárias.
     * POST /api/rh/payroll-runs/{id}/process
     */
    @PostMapping("/payroll-runs/{id}/process")
    public ResponseEntity<Void> processPayrollRun(@PathVariable("id") UUID id) {
        payrollService.processPayrollRun(id);
        return ResponseEntity.ok().build();
    }

    /**
     * Gera automaticamente os itens de folha para a execução.
     * POST /api/rh/payroll-runs/{id}/generate
     */
    @PostMapping("/payroll-runs/{id}/generate")
    public ResponseEntity<Void> generatePayrollItems(@PathVariable("id") UUID id) {
        payrollService.generatePayrollItems(id);
        return ResponseEntity.ok().build();
    }

    /**
     * Encerra definitivamente uma execução de folha.
     * POST /api/rh/payroll-runs/{id}/close
     */
    @PostMapping("/payroll-runs/{id}/close")
    public ResponseEntity<Void> closePayrollRun(@PathVariable("id") UUID id) {
        payrollService.closePayrollRun(id);
        return ResponseEntity.ok().build();
    }

    /**
     * Exclui uma execução de folha (apenas se status PENDING ou GENERATED).
     * DELETE /api/rh/payroll-runs/{id}
     */
    @DeleteMapping("/payroll-runs/{id}")
    public ResponseEntity<Void> deletePayrollRun(@PathVariable("id") UUID id) {
        payrollService.deletePayrollRun(id);
        return ResponseEntity.noContent().build();
    }

    /**
     * Diagnóstico: Verifica todos os requisitos para geração de itens.
     * GET /api/rh/payroll-runs/{id}/diagnose
     */
    @GetMapping("/payroll-runs/{id}/diagnose")
    public ResponseEntity<java.util.Map<String, Object>> diagnosePayrollRun(@PathVariable("id") UUID id) {
        try {
            java.util.Map<String, Object> diagnosis = payrollService.diagnosePayrollRun(id);
            return ResponseEntity.ok(diagnosis);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.notFound().build();
        }
    }
}
