package com.cameleer.server.app.storage;

import com.cameleer.server.app.AbstractPostgresIT;
import com.cameleer.server.core.runtime.Deployment;
import com.cameleer.server.core.runtime.DeploymentService;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.UUID;

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

class PostgresDeploymentRepositoryCreatedByIT extends AbstractPostgresIT {

    @Autowired DeploymentService deploymentService;
    @Autowired JdbcTemplate jdbc;

    private UUID appId;
    private UUID envId;
    private UUID versionId;

    @BeforeEach
    void seedAppAndVersion() {
        // Clean up to avoid conflicts across test runs
        jdbc.update("DELETE FROM deployments");
        jdbc.update("DELETE FROM app_versions");
        jdbc.update("DELETE FROM apps");
        jdbc.update("DELETE FROM users WHERE user_id IN ('alice', 'bob')");

        envId = jdbc.queryForObject(
            "SELECT id FROM environments WHERE slug = 'default'", UUID.class);

        // Seed users (alice, bob) — use the bare user_id convention; provider is NOT NULL
        jdbc.update("INSERT INTO users (user_id, provider) VALUES (?, 'LOCAL') " +
                    "ON CONFLICT (user_id) DO NOTHING", "alice");
        jdbc.update("INSERT INTO users (user_id, provider) VALUES (?, 'LOCAL') " +
                    "ON CONFLICT (user_id) DO NOTHING", "bob");

        // Seed app
        appId = UUID.randomUUID();
        jdbc.update("INSERT INTO apps (id, environment_id, slug, display_name) " +
                    "VALUES (?, ?, 'test-app', 'Test App')",
                    appId, envId);

        // Seed version
        versionId = UUID.randomUUID();
        jdbc.update("INSERT INTO app_versions (id, app_id, version, jar_path, jar_checksum) " +
                    "VALUES (?, ?, 1, '/tmp/x.jar', 'abc')",
                    versionId, appId);
    }

    @AfterEach
    void cleanup() {
        jdbc.update("DELETE FROM deployments");
        jdbc.update("DELETE FROM app_versions");
        jdbc.update("DELETE FROM apps");
        jdbc.update("DELETE FROM users WHERE user_id IN ('alice', 'bob')");
    }

    @Test
    void createDeployment_persists_createdBy_and_returns_it() {
        Deployment d = deploymentService.createDeployment(appId, versionId, envId, "alice");
        assertThat(d.createdBy()).isEqualTo("alice");
        String fromDb = jdbc.queryForObject(
            "SELECT created_by FROM deployments WHERE id = ?", String.class, d.id());
        assertThat(fromDb).isEqualTo("alice");
    }

    @Test
    void promote_persists_createdBy() {
        Deployment promoted = deploymentService.promote(appId, versionId, envId, "bob");
        assertThat(promoted.createdBy()).isEqualTo("bob");
    }
}
