package br.gov.sigefp.budget.api;

import br.gov.sigefp.budget.api.dto.BudgetEntryDTO;
import br.gov.sigefp.budget.api.dto.CreateBudgetEntryDTO;
import br.gov.sigefp.budget.service.BudgetEntryService;
import br.gov.sigefp.common.exception.BusinessException;
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;

@RestController
@RequestMapping("/api/budget/entries")
@RequiredArgsConstructor
@Slf4j
public class BudgetEntryController {

    private final BudgetEntryService budgetEntryService;

    @PostMapping
    public ResponseEntity<BudgetEntryDTO> create(@Valid @RequestBody CreateBudgetEntryDTO dto) {
        try {
            BudgetEntryDTO created = budgetEntryService.create(dto);
            return ResponseEntity.status(HttpStatus.CREATED).body(created);
        } catch (ResourceNotFoundException e) {
            log.warn("Recurso não encontrado ao criar entrada orçamentária: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        } catch (BusinessException e) {
            log.warn("Erro de negócio ao criar entrada orçamentária: {}", e.getMessage());
            return ResponseEntity.status(e.getStatus()).build();
        } catch (Exception e) {
            log.error("Erro inesperado ao criar entrada orçamentária", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @GetMapping
    public ResponseEntity<Page<BudgetEntryDTO>> findByBudgetLine(
            @RequestParam(name = "budgetLineId") UUID budgetLineId,
            @RequestParam(name = "page", defaultValue = "0") int page,
            @RequestParam(name = "size", defaultValue = "20") int size,
            @RequestParam(name = "sortBy", defaultValue = "transactionDate") String sortBy,
            @RequestParam(name = "sortDirection", defaultValue = "DESC") String sortDirection) {

        Sort sort = Sort.by(Sort.Direction.fromString(sortDirection), sortBy);
        Pageable pageable = PageRequest.of(page, size, sort);

        Page<BudgetEntryDTO> result = budgetEntryService.findByBudgetLineId(budgetLineId, pageable);
        return ResponseEntity.ok(result);
    }
}
