package br.gov.sigefp.treasury.api;

import br.gov.sigefp.treasury.api.dto.CashAccountDTO;
import br.gov.sigefp.treasury.api.dto.CreateCashAccountDTO;
import br.gov.sigefp.treasury.service.CashAccountService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/treasury/cash-accounts")
@RequiredArgsConstructor
public class CashAccountController {

    private final CashAccountService cashAccountService;

    @PostMapping
    public ResponseEntity<CashAccountDTO> create(@Valid @RequestBody CreateCashAccountDTO dto) {
        CashAccountDTO created = cashAccountService.create(dto);
        return ResponseEntity.status(HttpStatus.CREATED).body(created);
    }

    @GetMapping("/{id}")
    public ResponseEntity<CashAccountDTO> findById(@PathVariable UUID id) {
        CashAccountDTO account = cashAccountService.findById(id);
        return ResponseEntity.ok(account);
    }

    @GetMapping
    public ResponseEntity<List<CashAccountDTO>> findAll(
            @RequestParam(name = "type", required = false) String type,
            @RequestParam(name = "activeOnly", required = false, defaultValue = "true") Boolean activeOnly) {
        List<CashAccountDTO> accounts;
        if (type != null) {
            accounts = cashAccountService.findByType(type);
        } else if (activeOnly) {
            accounts = cashAccountService.findActive();
        } else {
            accounts = cashAccountService.findAll();
        }
        return ResponseEntity.ok(accounts);
    }

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

    @GetMapping("/{id}/current-balance")
    public ResponseEntity<BigDecimal> getCurrentBalance(@PathVariable UUID id) {
        BigDecimal balance = cashAccountService.getCurrentBalance(id);
        return ResponseEntity.ok(balance);
    }
}
