package de.fete.adapter.out.persistence;

import de.fete.domain.model.Rsvp;
import de.fete.domain.model.RsvpToken;
import de.fete.domain.port.out.RsvpRepository;
import java.util.List;
import org.springframework.stereotype.Repository;

/** Persistence adapter implementing the RsvpRepository outbound port. */
@Repository
public class RsvpPersistenceAdapter implements RsvpRepository {

  private final RsvpJpaRepository jpaRepository;

  /** Creates a new adapter with the given JPA repository. */
  public RsvpPersistenceAdapter(RsvpJpaRepository jpaRepository) {
    this.jpaRepository = jpaRepository;
  }

  @Override
  public Rsvp save(Rsvp rsvp) {
    RsvpJpaEntity entity = toEntity(rsvp);
    RsvpJpaEntity saved = jpaRepository.save(entity);
    return toDomain(saved);
  }

  @Override
  public long countByEventId(Long eventId) {
    return jpaRepository.countByEventId(eventId);
  }

  @Override
  public List<Rsvp> findByEventId(Long eventId) {
    return jpaRepository.findAllByEventIdOrderByIdAsc(eventId).stream()
        .map(this::toDomain)
        .toList();
  }

  @Override
  public boolean deleteByEventIdAndRsvpToken(Long eventId, RsvpToken rsvpToken) {
    return jpaRepository.deleteByEventIdAndRsvpToken(eventId, rsvpToken.value()) > 0;
  }

  private RsvpJpaEntity toEntity(Rsvp rsvp) {
    var entity = new RsvpJpaEntity();
    entity.setId(rsvp.id());
    entity.setRsvpToken(rsvp.rsvpToken().value());
    entity.setEventId(rsvp.eventId());
    entity.setName(rsvp.name());
    return entity;
  }

  private Rsvp toDomain(RsvpJpaEntity entity) {
    return new Rsvp(
        entity.getId(),
        new RsvpToken(entity.getRsvpToken()),
        entity.getEventId(),
        entity.getName());
  }
}
