using ColaFlow.Modules.Mcp.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace ColaFlow.Modules.Mcp.Infrastructure.Persistence.Configurations;

/// <summary>
/// EF Core configuration for TaskLock entity
/// </summary>
public class TaskLockConfiguration : IEntityTypeConfiguration<TaskLock>
{
    public void Configure(EntityTypeBuilder<TaskLock> builder)
    {
        builder.ToTable("task_locks");

        builder.HasKey(t => t.Id);

        builder.Property(t => t.Id)
            .HasColumnName("id")
            .IsRequired();

        builder.Property(t => t.TenantId)
            .HasColumnName("tenant_id")
            .IsRequired();

        builder.Property(t => t.ResourceType)
            .HasColumnName("resource_type")
            .HasMaxLength(200)
            .IsRequired();

        builder.Property(t => t.ResourceId)
            .HasColumnName("resource_id")
            .IsRequired();

        builder.Property(t => t.LockHolderType)
            .HasColumnName("lock_holder_type")
            .HasMaxLength(50)
            .IsRequired();

        builder.Property(t => t.LockHolderId)
            .HasColumnName("lock_holder_id")
            .IsRequired();

        builder.Property(t => t.LockHolderName)
            .HasColumnName("lock_holder_name")
            .HasMaxLength(500);

        builder.Property(t => t.Purpose)
            .HasColumnName("purpose")
            .HasMaxLength(1000);

        builder.Property(t => t.AcquiredAt)
            .HasColumnName("acquired_at")
            .IsRequired();

        builder.Property(t => t.ExpiresAt)
            .HasColumnName("expires_at")
            .IsRequired();

        builder.Property(t => t.Status)
            .HasColumnName("status")
            .HasConversion<string>()
            .HasMaxLength(50)
            .IsRequired();

        builder.Property(t => t.ReleasedAt)
            .HasColumnName("released_at");

        // Indexes
        builder.HasIndex(t => new { t.TenantId, t.ResourceType, t.ResourceId })
            .HasDatabaseName("ix_task_locks_resource")
            .IsUnique();

        builder.HasIndex(t => t.Status)
            .HasDatabaseName("ix_task_locks_status");

        builder.HasIndex(t => t.ExpiresAt)
            .HasDatabaseName("ix_task_locks_expires_at");

        builder.HasIndex(t => t.LockHolderId)
            .HasDatabaseName("ix_task_locks_lock_holder_id");

        // Ignore domain events
        builder.Ignore(t => t.DomainEvents);
    }
}
