package fr.marouse.repository.jpa;

import java.util.List;
import java.util.Optional;

import fr.marouse.entity.Client;
import fr.marouse.entity.Compte;
import fr.marouse.repository.ClientRepository;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityTransaction;

public class ClientRepositoryJPA implements ClientRepository {

    private final EntityManager em;

    public ClientRepositoryJPA(EntityManager em) {
        this.em = em;
    }

    @Override
    public void save(Client client) {
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            em.persist(client);
            tx.commit();
        } catch (Exception e) {
            if (tx.isActive()) tx.rollback();
            throw e;
        }
    }

    @Override
    public Optional<Client> findById(int id) {
        return Optional.ofNullable(em.find(Client.class, id));
    }

    @Override
    public List<Client> findAll() {
        return em.createQuery(
                "SELECT c FROM Client c",
                Client.class
        ).getResultList();
    }

    @Override
    public List<Compte> findComptesByClient(int idClient) {
        return em.createQuery(
                "SELECT c FROM Client cl JOIN cl.comptes c WHERE cl.numClient = :id",
                Compte.class
        )
        .setParameter("id", idClient)
        .getResultList();
    }
}
