package br.gov.sigefp.treasury.api;

import br.gov.sigefp.common.exception.ResourceNotFoundException;
import br.gov.sigefp.treasury.api.dto.CreateTreasuryPlanDTO;
import br.gov.sigefp.treasury.api.dto.TreasuryPlanDTO;
import br.gov.sigefp.treasury.service.TreasuryPlanService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.UUID;

/**
 * Controller REST para gestão de Planos de Tesouraria.
 * Conforme Master Plan - Module 2: Preventive Control.
 */
@RestController
@RequestMapping("/api/treasury/plans")
@RequiredArgsConstructor
@Slf4j
public class TreasuryPlanController {

    private final TreasuryPlanService treasuryPlanService;

    @PostMapping
    public ResponseEntity<TreasuryPlanDTO> create(@Valid @RequestBody CreateTreasuryPlanDTO dto) {
        TreasuryPlanDTO created = treasuryPlanService.createPlan(dto);
        return ResponseEntity.status(HttpStatus.CREATED).body(created);
    }

    @GetMapping("/{id}")
    public ResponseEntity<TreasuryPlanDTO> findById(@PathVariable UUID id) {
        try {
            TreasuryPlanDTO plan = treasuryPlanService.findById(id);
            return ResponseEntity.ok(plan);
        } catch (ResourceNotFoundException e) {
            log.warn("Plano não encontrado: {}", id);
            return ResponseEntity.notFound().build();
        }
    }

    @GetMapping("/status/{status}")
    public ResponseEntity<List<TreasuryPlanDTO>> findByStatus(@PathVariable String status) {
        List<TreasuryPlanDTO> plans = treasuryPlanService.findByStatus(status);
        return ResponseEntity.ok(plans);
    }

    @GetMapping("/active")
    public ResponseEntity<TreasuryPlanDTO> findActivePlan(
            @RequestParam(required = false) String date) {
        try {
            LocalDate searchDate;
            if (date != null) {
                try {
                    searchDate = LocalDate.parse(date);
                } catch (DateTimeParseException e) {
                    log.warn("Data inválida fornecida: {}", date);
                    return ResponseEntity.badRequest().build();
                }
            } else {
                searchDate = LocalDate.now();
            }
            
            TreasuryPlanDTO plan = treasuryPlanService.findActivePlanForDate(searchDate);
            if (plan == null) {
                return ResponseEntity.notFound().build();
            }
            return ResponseEntity.ok(plan);
        } catch (Exception e) {
            log.error("Erro ao buscar plano ativo", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @PutMapping("/{id}/approve")
    public ResponseEntity<TreasuryPlanDTO> approve(
            @PathVariable UUID id,
            @RequestParam UUID approverId) {
        try {
            TreasuryPlanDTO approved = treasuryPlanService.approvePlan(id, approverId);
            return ResponseEntity.ok(approved);
        } catch (ResourceNotFoundException e) {
            log.warn("Plano não encontrado para aprovação: {}", id);
            return ResponseEntity.notFound().build();
        } catch (Exception e) {
            log.error("Erro ao aprovar plano: {}", id, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}

