using ClaudeDo.Data.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;

namespace ClaudeDo.Data.Configuration;

public class WorktreeEntityConfiguration : IEntityTypeConfiguration<WorktreeEntity>
{
    private static string StateToString(WorktreeState v)
        => v == WorktreeState.Active ? "active"
         : v == WorktreeState.Merged ? "merged"
         : v == WorktreeState.Discarded ? "discarded"
         : v == WorktreeState.Kept ? "kept"
         : throw new ArgumentOutOfRangeException(nameof(v));

    private static WorktreeState StateFromString(string v)
        => v == "active" ? WorktreeState.Active
         : v == "merged" ? WorktreeState.Merged
         : v == "discarded" ? WorktreeState.Discarded
         : v == "kept" ? WorktreeState.Kept
         : throw new ArgumentOutOfRangeException(nameof(v));

    private static readonly ValueConverter<WorktreeState, string> StateConverter =
        new(v => StateToString(v), v => StateFromString(v));

    public void Configure(EntityTypeBuilder<WorktreeEntity> builder)
    {
        builder.ToTable("worktrees");

        builder.HasKey(w => w.TaskId);
        builder.Property(w => w.TaskId).HasColumnName("task_id");
        builder.Property(w => w.Path).HasColumnName("path").IsRequired();
        builder.Property(w => w.BranchName).HasColumnName("branch_name").IsRequired();
        builder.Property(w => w.BaseCommit).HasColumnName("base_commit").IsRequired();
        builder.Property(w => w.HeadCommit).HasColumnName("head_commit");
        builder.Property(w => w.DiffStat).HasColumnName("diff_stat");
        builder.Property(w => w.MergeCommit).HasColumnName("merge_commit");
        builder.Property(w => w.State).HasColumnName("state").IsRequired()
            .HasDefaultValue(WorktreeState.Active)
            .HasConversion(StateConverter);
        builder.Property(w => w.CreatedAt).HasColumnName("created_at").IsRequired();
    }
}
