package vassistent.service;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import vassistent.model.DatabaseEntry;

import java.nio.file.Path;
import java.util.List;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

/**
 * Integration tests for {@link DataPersistenceService} using an isolated temp SQLite database.
 */
class DataPersistenceServiceTest {

    @TempDir
    Path tempDir;

    private DataPersistenceService service;
    private String dbUrl;

    /**
     * Creates an isolated test database for each test.
     */
    @BeforeEach
    void setUp() {
        dbUrl = "jdbc:sqlite:" + tempDir.resolve("health-test.db").toAbsolutePath();
        service = new DataPersistenceService(dbUrl);
    }

    /**
     * Verifies the configured JDBC URL is exposed unchanged.
     */
    @Test
    void getDbUrl_returnsConfiguredUrl() {
        assertEquals(dbUrl, service.getDbUrl());
    }

    /**
     * Verifies that stored entries can be read back in chronological order.
     *
     * @throws InterruptedException if the sleep used to separate timestamps is interrupted
     */
    @Test
    void store_andGetLastEntries_returnsChronologicalEntries() throws InterruptedException {
        service.store(1);
        Thread.sleep(5);
        service.store(0);

        List<DatabaseEntry> entries = service.getLastEntries(10);

        assertEquals(2, entries.size());
        assertEquals(1.0, entries.get(0).getValue());
        assertEquals(0.0, entries.get(1).getValue());
        assertNotNull(entries.get(0).getTimestamp());
        assertNotNull(entries.get(1).getTimestamp());
    }

    /**
     * Verifies that entry retrieval respects the requested limit.
     */
    @Test
    void getLastEntries_respectsLimit() throws InterruptedException {
        service.store(1);
        Thread.sleep(5);
        service.store(0);
        Thread.sleep(5);
        service.store(1);

        List<DatabaseEntry> entries = service.getLastEntries(2);

        assertEquals(2, entries.size());
        assertFalse(entries.isEmpty());
    }

    /**
     * Verifies that initializing the service ensures the data folder exists.
     */
    @Test
    void constructor_createsDataFolderIfMissing() {
        assertTrue(java.nio.file.Files.exists(Path.of("data")));
    }
}
