package de.fete.adapter.out.persistence;

import de.fete.domain.model.Event;
import de.fete.domain.model.EventToken;
import de.fete.domain.model.OrganizerToken;
import de.fete.domain.port.out.EventRepository;
import java.time.ZoneId;
import java.util.Optional;
import org.springframework.stereotype.Repository;

/** Persistence adapter implementing the EventRepository outbound port. */
@Repository
public class EventPersistenceAdapter implements EventRepository {

  private final EventJpaRepository jpaRepository;

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

  @Override
  public Event save(Event event) {
    EventJpaEntity entity = toEntity(event);
    EventJpaEntity saved = jpaRepository.save(entity);
    return toDomain(saved);
  }

  @Override
  public Optional<Event> findByEventToken(EventToken eventToken) {
    return jpaRepository.findByEventToken(eventToken.value()).map(this::toDomain);
  }

  @Override
  public int deleteExpired() {
    return jpaRepository.deleteExpired();
  }

  private EventJpaEntity toEntity(Event event) {
    var entity = new EventJpaEntity();
    entity.setId(event.id());
    entity.setEventToken(event.eventToken().value());
    entity.setOrganizerToken(event.organizerToken().value());
    entity.setTitle(event.title());
    entity.setDescription(event.description());
    entity.setDateTime(event.dateTime());
    entity.setTimezone(event.timezone().getId());
    entity.setLocation(event.location());
    entity.setExpiryDate(event.expiryDate());
    entity.setCreatedAt(event.createdAt());
    entity.setCancelled(event.cancelled());
    entity.setCancellationReason(event.cancellationReason());
    return entity;
  }

  private Event toDomain(EventJpaEntity entity) {
    return new Event(
        entity.getId(),
        new EventToken(entity.getEventToken()),
        new OrganizerToken(entity.getOrganizerToken()),
        entity.getTitle(),
        entity.getDescription(),
        entity.getDateTime(),
        ZoneId.of(entity.getTimezone()),
        entity.getLocation(),
        entity.getExpiryDate(),
        entity.getCreatedAt(),
        entity.isCancelled(),
        entity.getCancellationReason());
  }
}
