using ClaudeDo.Data.Models;
using ClaudeDo.Data.Repositories;
using Microsoft.EntityFrameworkCore;

namespace ClaudeDo.Data.Tests;

public sealed class PrimeScheduleRepositoryTests : IDisposable
{
    private readonly string _dbPath;
    private readonly ClaudeDoDbContext _ctx;
    private readonly PrimeScheduleRepository _repo;

    public PrimeScheduleRepositoryTests()
    {
        _dbPath = Path.Combine(Path.GetTempPath(), $"claudedo_prime_{Guid.NewGuid():N}.db");
        var options = new DbContextOptionsBuilder<ClaudeDoDbContext>()
            .UseSqlite($"Data Source={_dbPath}")
            .Options;
        _ctx = new ClaudeDoDbContext(options);
        _ctx.Database.EnsureCreated();
        _repo = new PrimeScheduleRepository(_ctx);
    }

    public void Dispose()
    {
        _ctx.Dispose();
        foreach (var suffix in new[] { "", "-wal", "-shm" })
            try { File.Delete(_dbPath + suffix); } catch { }
    }

    [Fact]
    public async Task UpsertAsync_then_GetAsync_roundtrips_the_prompt_override()
    {
        var entity = new PrimeScheduleEntity { PromptOverride = "Also prioritize anything tagged #urgent." };

        await _repo.UpsertAsync(entity);
        var found = await _repo.GetAsync(entity.Id);

        Assert.NotNull(found);
        Assert.Equal("Also prioritize anything tagged #urgent.", found!.PromptOverride);
    }

    [Fact]
    public async Task UpsertAsync_with_null_override_persists_as_null()
    {
        var entity = new PrimeScheduleEntity { PromptOverride = null };

        await _repo.UpsertAsync(entity);
        var found = await _repo.GetAsync(entity.Id);

        Assert.NotNull(found);
        Assert.Null(found!.PromptOverride);
    }

    [Fact]
    public async Task UpsertAsync_updates_the_override_on_an_existing_row()
    {
        var entity = new PrimeScheduleEntity { PromptOverride = "old override" };
        await _repo.UpsertAsync(entity);

        entity.PromptOverride = "new override";
        await _repo.UpsertAsync(entity);

        var found = await _repo.GetAsync(entity.Id);
        Assert.Equal("new override", found!.PromptOverride);
    }
}
