package br.gov.sigefp.treasury.api;

import br.gov.sigefp.treasury.api.dto.CreateTreasuryPaymentDTO;
import br.gov.sigefp.treasury.api.dto.TreasuryPaymentDTO;
import br.gov.sigefp.treasury.service.TreasuryPaymentService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
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.List;
import java.util.UUID;

/**
 * Controller REST para gestão de pagamentos efetivados pela tesouraria.
 */
@RestController
@RequestMapping("/api/treasury/payments")
@RequiredArgsConstructor
public class TreasuryPaymentController {

    private final TreasuryPaymentService treasuryPaymentService;

    @GetMapping
    public ResponseEntity<?> findAll(
            @RequestParam(name = "paymentOrderId", required = false) UUID paymentOrderId,
            @RequestParam(name = "status", required = false) String status,
            @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) {

        // Se há filtros, retornar lista (sem paginação)
        if (paymentOrderId != null || status != null) {
            List<TreasuryPaymentDTO> result;
            if (paymentOrderId != null && status != null) {
                result = treasuryPaymentService.findByPaymentOrderIdAndStatus(paymentOrderId, status);
            } else if (paymentOrderId != null) {
                result = treasuryPaymentService.findByPaymentOrderId(paymentOrderId);
            } else {
                result = treasuryPaymentService.findByStatus(status);
            }
            return ResponseEntity.ok(result);
        }

        // Sem filtros, retornar paginado
        Sort sort = sortBy != null
                ? Sort.by(Sort.Direction.fromString(sortDirection), sortBy)
                : Sort.by(Sort.Direction.DESC, "paidAt");

        Pageable pageable = PageRequest.of(page, size, sort);
        Page<TreasuryPaymentDTO> result = treasuryPaymentService.findAll(pageable);
        return ResponseEntity.ok(result);
    }

    @PostMapping
    public ResponseEntity<TreasuryPaymentDTO> registerPayment(@Valid @RequestBody CreateTreasuryPaymentDTO dto) {
        try {
            TreasuryPaymentDTO created = treasuryPaymentService.registerPayment(dto);
            return ResponseEntity.status(HttpStatus.CREATED).body(created);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        }
    }
}
