package br.gov.sigefp.treasury.api;

import br.gov.sigefp.treasury.api.dto.CreatePaymentBatchDTO;
import br.gov.sigefp.treasury.api.dto.PaymentBatchDTO;
import br.gov.sigefp.treasury.api.dto.UpdateStatusDTO;
import br.gov.sigefp.treasury.service.PaymentBatchService;
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 lotes de pagamento.
 */
@RestController
@RequestMapping("/api/treasury/payment-batches")
@RequiredArgsConstructor
public class PaymentBatchController {

    private final PaymentBatchService paymentBatchService;

    @GetMapping
    public ResponseEntity<?> findAll(
            @RequestParam(name = "periodId", required = false) Long periodId,
            @RequestParam(name = "ministryId", required = false) UUID ministryId,
            @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 (periodId != null || ministryId != null || status != null) {
            List<PaymentBatchDTO> result;
            if (periodId != null && ministryId != null) {
                result = paymentBatchService.findByPeriodIdAndMinistryId(periodId, ministryId);
                if (status != null) {
                    result = result.stream()
                            .filter(pb -> status.equals(pb.getStatus()))
                            .toList();
                }
            } else if (periodId != null && status != null) {
                result = paymentBatchService.findByPeriodIdAndStatus(periodId, status);
            } else if (ministryId != null && status != null) {
                result = paymentBatchService.findByMinistryIdAndStatus(ministryId, status);
            } else if (periodId != null) {
                result = paymentBatchService.findByPeriodId(periodId);
            } else if (ministryId != null) {
                result = paymentBatchService.findByMinistryId(ministryId);
            } else {
                result = paymentBatchService.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, "createdAt");

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

    @GetMapping("/{id}")
    public ResponseEntity<PaymentBatchDTO> findById(@PathVariable UUID id) {
        try {
            PaymentBatchDTO dto = paymentBatchService.findById(id);
            return ResponseEntity.ok(dto);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.notFound().build();
        }
    }

    @PostMapping
    public ResponseEntity<PaymentBatchDTO> create(@Valid @RequestBody CreatePaymentBatchDTO dto) {
        try {
            PaymentBatchDTO created = paymentBatchService.create(dto);
            return ResponseEntity.status(HttpStatus.CREATED).body(created);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @PostMapping("/{id}/status")
    public ResponseEntity<PaymentBatchDTO> updateStatus(
            @PathVariable UUID id,
            @Valid @RequestBody UpdateStatusDTO dto) {
        try {
            PaymentBatchDTO updated = paymentBatchService.updateStatus(id, dto.getStatus());
            return ResponseEntity.ok(updated);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        }
    }
}
