using System.IO;
using ClaudeDo.Data;
using ClaudeDo.Installer.Core;
using Microsoft.EntityFrameworkCore;

namespace ClaudeDo.Installer.Steps;

public sealed class InitDatabaseStep : IInstallStep
{
    public string Name => "Initialize Database";

    public Task<StepResult> ExecuteAsync(InstallContext ctx, IProgress<string> progress, CancellationToken ct)
    {
        try
        {
            var expandedPath = Paths.Expand(ctx.DbPath);
            progress.Report($"Initializing database at {expandedPath}");

            var parent = Path.GetDirectoryName(expandedPath);
            if (!string.IsNullOrEmpty(parent))
                Directory.CreateDirectory(parent);

            var options = new DbContextOptionsBuilder<ClaudeDoDbContext>()
                .UseSqlite($"Data Source={expandedPath}")
                .Options;
            using var context = new ClaudeDoDbContext(options);
            ClaudeDoDbContext.MigrateAndConfigure(context);

            progress.Report("Schema applied successfully");
            return Task.FromResult(StepResult.Ok());
        }
        catch (Exception ex)
        {
            return Task.FromResult(StepResult.Fail(ex.Message));
        }
    }
}
