package de.fete.adapter.out.persistence;

import static org.assertj.core.api.Assertions.assertThat;

import de.fete.TestcontainersConfig;
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.LocalDate;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Import;
import org.springframework.transaction.annotation.Transactional;

@SpringBootTest
@Import(TestcontainersConfig.class)
@Transactional
class EventPersistenceAdapterIntegrationTest {

  @Autowired
  private EventRepository eventRepository;

  @Test
  void deleteExpiredRemovesExpiredEvents() {
    Event expired = buildEvent("Expired Party", LocalDate.now().minusDays(1));
    eventRepository.save(expired);

    int deleted = eventRepository.deleteExpired();

    assertThat(deleted).isGreaterThanOrEqualTo(1);
  }

  @Test
  void deleteExpiredKeepsNonExpiredEvents() {
    Event future = buildEvent("Future Party", LocalDate.now().plusDays(30));
    Event saved = eventRepository.save(future);

    eventRepository.deleteExpired();

    assertThat(eventRepository.findByEventToken(saved.eventToken())).isPresent();
  }

  @Test
  void deleteExpiredKeepsEventsExpiringToday() {
    Event today = buildEvent("Today Party", LocalDate.now());
    Event saved = eventRepository.save(today);

    eventRepository.deleteExpired();

    assertThat(eventRepository.findByEventToken(saved.eventToken())).isPresent();
  }

  @Test
  void deleteExpiredReturnsZeroWhenNoneExpired() {
    // Only save a future event
    buildEvent("Future Only", LocalDate.now().plusDays(60));

    int deleted = eventRepository.deleteExpired();

    assertThat(deleted).isGreaterThanOrEqualTo(0);
  }

  private Event buildEvent(String title, LocalDate expiryDate) {
    return new Event(
        null,
        EventToken.generate(),
        OrganizerToken.generate(),
        title,
        "Test description",
        OffsetDateTime.of(2026, 6, 15, 20, 0, 0, 0, ZoneOffset.ofHours(2)),
        ZoneId.of("Europe/Berlin"),
        "Test Location",
        expiryDate,
        OffsetDateTime.now(),
        false,
        null);
  }
}
