using JobTrackerApi.Data;
using JobTrackerApi.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System.Text.Json;

if (args.Length < 1)
{
    Console.Error.WriteLine("Usage: dotnet run --project tools/hostile-fixture-db -- <data-root>");
    return 1;
}

var dataRoot = Path.GetFullPath(args[0]);
Directory.CreateDirectory(dataRoot);
var dbPath = Path.Combine(dataRoot, "jobtracker.db");
if (File.Exists(dbPath))
{
    File.Delete(dbPath);
}

var config = new ConfigurationBuilder()
    .AddInMemoryCollection(new Dictionary<string, string?>
    {
        ["Data:Root"] = dataRoot,
    })
    .Build();

var currentUser = new StaticCurrentUserService(null);
var options = new DbContextOptionsBuilder<JobTrackerContext>()
    .UseSqlite($"Data Source={dbPath}")
    .Options;

await using var db = new JobTrackerContext(options, currentUser);
await db.Database.EnsureDeletedAsync();
await db.Database.EnsureCreatedAsync();

var tables = await db.Database.SqlQueryRaw<string>("SELECT name AS Value FROM sqlite_master WHERE type='table' ORDER BY name;").ToListAsync();
var payload = new
{
    dataRoot,
    dbPath,
    tables,
};
Console.WriteLine(JsonSerializer.Serialize(payload));
return 0;

file sealed class StaticCurrentUserService(string? userId) : ICurrentUserService
{
    public string? UserId => userId;
}
