package br.gov.sigefp.treasury.api;

import br.gov.sigefp.treasury.api.dto.CreateTreasuryEntryDTO;
import br.gov.sigefp.treasury.api.dto.TreasuryEntryDTO;
import br.gov.sigefp.treasury.domain.TreasuryEntryType;
import br.gov.sigefp.treasury.service.TreasuryEntryService;
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.math.BigDecimal;
import java.util.UUID;

@RestController
@RequestMapping("/api/treasury/entries")
@RequiredArgsConstructor
public class TreasuryEntryController {

    private final TreasuryEntryService treasuryEntryService;

    @PostMapping
    public ResponseEntity<TreasuryEntryDTO> create(@Valid @RequestBody CreateTreasuryEntryDTO dto) {
        TreasuryEntryDTO created = treasuryEntryService.create(dto);
        return ResponseEntity.status(HttpStatus.CREATED).body(created);
    }

    @GetMapping("/{id}")
    public ResponseEntity<TreasuryEntryDTO> findById(@PathVariable UUID id) {
        TreasuryEntryDTO entry = treasuryEntryService.findById(id);
        return ResponseEntity.ok(entry);
    }

    @GetMapping
    public ResponseEntity<Page<TreasuryEntryDTO>> findAll(
            @RequestParam(required = false) UUID cashAccountId,
            @RequestParam(required = false) TreasuryEntryType type,
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(defaultValue = "transactionDate") String sortBy,
            @RequestParam(defaultValue = "DESC") String sortDirection) {

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

        Page<TreasuryEntryDTO> result;
        if (cashAccountId != null) {
            result = treasuryEntryService.findByCashAccountId(cashAccountId, pageable);
        } else if (type != null) {
            result = treasuryEntryService.findByType(type, pageable);
        } else if (status != null) {
            result = treasuryEntryService.findByStatus(status, pageable);
        } else {
            // Retornar vazio se nenhum filtro for fornecido
            result = Page.empty(pageable);
        }

        return ResponseEntity.ok(result);
    }

    @GetMapping("/{cashAccountId}/available-balance")
    public ResponseEntity<BigDecimal> getAvailableBalance(@PathVariable UUID cashAccountId) {
        BigDecimal balance = treasuryEntryService.calculateAvailableBalance(cashAccountId);
        return ResponseEntity.ok(balance);
    }
}

