package br.gov.sigefp.budget.api;

import br.gov.sigefp.budget.api.dto.BudgetExecutionDTO;
import br.gov.sigefp.budget.service.BudgetExecutionService;
import br.gov.sigefp.common.exception.BusinessException;
import br.gov.sigefp.common.exception.InsufficientBudgetException;
import br.gov.sigefp.common.exception.ResourceNotFoundException;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

/**
 * Controller REST para gestão de execuções orçamentárias.
 */
@RestController
@RequestMapping("/api/budget/execution")
@RequiredArgsConstructor
@Slf4j
public class BudgetExecutionController {

    private final BudgetExecutionService budgetExecutionService;

    @GetMapping
    public ResponseEntity<?> findAll(
            @RequestParam(name = "budgetLineId", required = false) UUID budgetLineId,
            @RequestParam(name = "periodId", required = false) Long periodId,
            @RequestParam(name = "movementType", required = false) String movementType,
            @RequestParam(name = "page", defaultValue = "0") int page,
            @RequestParam(name = "size", defaultValue = "20") int size,
            @RequestParam(name = "sortBy", required = false) String sortBy,
            @RequestParam(name = "sortDirection", required = false, defaultValue = "DESC") String sortDirection) {

        Sort sort = sortBy != null
                ? Sort.by(Sort.Direction.fromString(sortDirection), sortBy)
                : Sort.by(Sort.Direction.DESC, "createdAt");

        Pageable pageable = PageRequest.of(page, size, sort);

        Page<BudgetExecutionDTO> result = budgetExecutionService.findByFilters(
                budgetLineId, periodId, movementType, pageable);

        return ResponseEntity.ok(result);
    }

    @PostMapping
    public ResponseEntity<BudgetExecutionDTO> registerExecution(@Valid @RequestBody BudgetExecutionDTO dto) {
        try {
            BudgetExecutionDTO created = budgetExecutionService.registerExecution(dto);
            return ResponseEntity.status(HttpStatus.CREATED).body(created);
        } catch (ResourceNotFoundException e) {
            log.warn("Recurso não encontrado ao registrar execução: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        } catch (InsufficientBudgetException e) {
            log.warn("Saldo insuficiente ao registrar execução: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.CONFLICT).build();
        } catch (BusinessException e) {
            log.warn("Erro de negócio ao registrar execução: {}", e.getMessage());
            return ResponseEntity.status(e.getStatus()).build();
        } catch (Exception e) {
            log.error("Erro inesperado ao registrar execução", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}
