package br.gov.sigefp.budget.api;

import br.gov.sigefp.budget.api.dto.BudgetLineDTO;
import br.gov.sigefp.budget.service.BudgetLineService;
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;

/**
 * Controller REST para gestão de linhas orçamentárias.
 */
@RestController
@RequestMapping("/api/budget/lines")
@RequiredArgsConstructor
@Slf4j
public class BudgetLineController {

    private final BudgetLineService budgetLineService;

    @GetMapping
    public ResponseEntity<Page<BudgetLineDTO>> findAll(
            @RequestParam(name = "fiscalYearId", required = false) UUID fiscalYearId,
            @RequestParam(name = "ministryId", required = false) UUID ministryId,
            @RequestParam(name = "orgUnitId", required = false) UUID orgUnitId,
            @RequestParam(name = "search", required = false) String search,
            @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 = "ASC") String sortDirection) {

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

        Pageable pageable = PageRequest.of(page, size, sort);
        Page<BudgetLineDTO> result = budgetLineService.findWithFilters(fiscalYearId, ministryId, orgUnitId, search,
                pageable);

        return ResponseEntity.ok(result);
    }

    @GetMapping("/{id}")
    public ResponseEntity<BudgetLineDTO> findById(@PathVariable UUID id) {
        try {
            BudgetLineDTO dto = budgetLineService.findById(id);
            return ResponseEntity.ok(dto);
        } catch (ResourceNotFoundException | IllegalArgumentException e) {
            log.warn("Recurso não encontrado ao buscar linha orçamentária: {}", id);
            return ResponseEntity.notFound().build();
        } catch (Exception e) {
            log.error("Erro inesperado ao buscar linha orçamentária", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @PostMapping
    public ResponseEntity<BudgetLineDTO> create(@Valid @RequestBody BudgetLineDTO dto) {
        try {
            BudgetLineDTO created = budgetLineService.create(dto);
            return ResponseEntity.status(HttpStatus.CREATED).body(created);
        } catch (BusinessException | IllegalArgumentException e) {
            log.warn("Erro de negócio ao criar linha orçamentária: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        } catch (Exception e) {
            log.error("Erro inesperado ao criar linha orçamentária", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<BudgetLineDTO> update(
            @PathVariable UUID id,
            @Valid @RequestBody BudgetLineDTO dto) {
        try {
            BudgetLineDTO updated = budgetLineService.update(id, dto);
            return ResponseEntity.ok(updated);
        } catch (ResourceNotFoundException | IllegalArgumentException e) {
            log.warn("Recurso não encontrado ao atualizar linha orçamentária: {}", id);
            return ResponseEntity.notFound().build();
        } catch (BusinessException e) {
            log.warn("Erro de negócio ao atualizar linha orçamentária: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        } catch (Exception e) {
            log.error("Erro inesperado ao atualizar linha orçamentária", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}
