package br.gov.sigefp.rh.service;

import br.gov.sigefp.rh.domain.Agent;
import br.gov.sigefp.rh.domain.AgentBankAccount;
import br.gov.sigefp.rh.repository.AgentBankAccountRepository;
import br.gov.sigefp.rh.repository.AgentRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Serviço para gestão de contas bancárias de agentes.
 */
@Service
@RequiredArgsConstructor
@Transactional
public class AgentBankAccountService {

    private final AgentBankAccountRepository repository;
    private final AgentRepository agentRepository;

    public AgentBankAccount save(AgentBankAccount account) {
        Agent agent = agentRepository.findById(account.getAgent().getId())
                .orElseThrow(
                        () -> new IllegalArgumentException("Agente não encontrado: " + account.getAgent().getId()));

        account.setAgent(agent);
        handlePrimaryStatus(account);
        return repository.save(account);
    }

    public AgentBankAccount update(AgentBankAccount account) {
        AgentBankAccount existing = repository.findById(account.getId())
                .orElseThrow(() -> new IllegalArgumentException("Conta bancária não encontrada: " + account.getId()));

        existing.setBank(account.getBank());
        existing.setBranchCode(account.getBranchCode());
        existing.setAccountNumber(account.getAccountNumber());
        existing.setIban(account.getIban());
        existing.setIsPrimary(account.getIsPrimary());

        handlePrimaryStatus(existing);
        return repository.save(existing);
    }

    private void handlePrimaryStatus(AgentBankAccount account) {
        if (Boolean.TRUE.equals(account.getIsPrimary())) {
            // Desativar outras contas primárias do mesmo agente
            List<AgentBankAccount> currentAccounts = repository.findByAgentId(account.getAgent().getId());
            for (AgentBankAccount existing : currentAccounts) {
                if (!existing.getId().equals(account.getId()) && Boolean.TRUE.equals(existing.getIsPrimary())) {
                    existing.setIsPrimary(false);
                    repository.save(existing);
                }
            }
        }
    }
}
