package br.gov.sigefp.treasury.api;

import br.gov.sigefp.treasury.api.dto.BankReconciliationDTO;
import br.gov.sigefp.treasury.api.dto.CreateBankReconciliationDTO;
import br.gov.sigefp.treasury.api.dto.ReconciliationItemDTO;
import br.gov.sigefp.treasury.service.BankReconciliationService;
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.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/treasury/reconciliations")
@RequiredArgsConstructor
public class BankReconciliationController {

    private final BankReconciliationService reconciliationService;

    @PostMapping
    public ResponseEntity<BankReconciliationDTO> importStatement(
            @Valid @RequestBody CreateBankReconciliationDTO dto) {
        BankReconciliationDTO created = reconciliationService.importStatement(dto);
        return ResponseEntity.status(HttpStatus.CREATED).body(created);
    }

    @PostMapping("/{id}/reconcile")
    public ResponseEntity<BankReconciliationDTO> reconcile(@PathVariable UUID id) {
        BankReconciliationDTO updated = reconciliationService.reconcile(id);
        return ResponseEntity.ok(updated);
    }

    @PostMapping("/{id}/match-item")
    public ResponseEntity<Void> matchItem(
            @PathVariable UUID id,
            @RequestParam UUID itemId,
            @RequestParam UUID systemTransactionId) {
        reconciliationService.matchItem(id, itemId, systemTransactionId);
        return ResponseEntity.ok().build();
    }

    @PostMapping("/{id}/finalize")
    public ResponseEntity<BankReconciliationDTO> finalize(
            @PathVariable UUID id,
            @RequestParam UUID reconciledBy) {
        BankReconciliationDTO updated = reconciliationService.finalize(id, reconciledBy);
        return ResponseEntity.ok(updated);
    }

    @GetMapping("/{id}")
    public ResponseEntity<BankReconciliationDTO> findById(@PathVariable UUID id) {
        BankReconciliationDTO reconciliation = reconciliationService.findById(id);
        return ResponseEntity.ok(reconciliation);
    }

    @GetMapping("/cash-account/{cashAccountId}")
    public ResponseEntity<List<BankReconciliationDTO>> findByCashAccountId(
            @PathVariable UUID cashAccountId) {
        List<BankReconciliationDTO> reconciliations = reconciliationService.findByCashAccountId(cashAccountId);
        return ResponseEntity.ok(reconciliations);
    }

    @GetMapping("/{id}/unmatched-items")
    public ResponseEntity<List<ReconciliationItemDTO>> findUnmatchedItems(
            @PathVariable UUID id) {
        List<ReconciliationItemDTO> items = reconciliationService.findUnmatchedItems(id);
        return ResponseEntity.ok(items);
    }
}

