package com.mosquito.project.persistence.repository;

import com.mosquito.project.persistence.entity.ActivityEntity;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.TestPropertySource;

import java.time.OffsetDateTime;
import java.time.ZoneOffset;

import static org.junit.jupiter.api.Assertions.*;

@DataJpaTest
@org.springframework.context.annotation.Import(com.mosquito.project.config.TestCacheConfig.class)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.ANY)
@TestPropertySource(properties = {
        "spring.cache.type=NONE",
        "spring.jpa.hibernate.ddl-auto=create-drop",
        "spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration"
})
class ActivityRepositoryTest {

    @Autowired
    private ActivityRepository activityRepository;

    @Test
    void whenSaveActivity_thenCanLoadIt() {
        OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
        ActivityEntity e = new ActivityEntity();
        e.setName("Repo Test Activity");
        e.setStartTimeUtc(now.plusDays(1));
        e.setEndTimeUtc(now.plusDays(2));
        e.setRewardCalculationMode("delta");
        e.setStatus("draft");
        e.setCreatedAt(now);
        e.setUpdatedAt(now);

        ActivityEntity saved = activityRepository.save(e);
        assertNotNull(saved.getId());

        ActivityEntity found = activityRepository.findById(saved.getId()).orElse(null);
        assertNotNull(found);
        assertEquals("Repo Test Activity", found.getName());
    }

    @Test
    void whenUpdateActivity_thenPersistedChangesVisible() {
        OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
        ActivityEntity e = new ActivityEntity();
        e.setName("Old Name");
        e.setStartTimeUtc(now.plusDays(1));
        e.setEndTimeUtc(now.plusDays(2));
        e.setRewardCalculationMode("delta");
        e.setStatus("draft");
        e.setCreatedAt(now);
        e.setUpdatedAt(now);
        ActivityEntity saved = activityRepository.save(e);

        saved.setName("New Name");
        saved.setUpdatedAt(now.plusMinutes(1));
        ActivityEntity updated = activityRepository.save(saved);

        ActivityEntity found = activityRepository.findById(updated.getId()).orElseThrow();
        assertEquals("New Name", found.getName());
    }
}
