using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ColaFlow.Modules.ProjectManagement.Domain.Aggregates.ProjectAggregate;
using ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using ColaFlow.Shared.Kernel.Common;

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

/// <summary>
/// Entity configuration for Epic entity
/// </summary>
public class EpicConfiguration : IEntityTypeConfiguration<Epic>
{
    public void Configure(EntityTypeBuilder<Epic> builder)
    {
        builder.ToTable("Epics");

        // Primary key
        builder.HasKey("Id");

        // Id conversion
        builder.Property(e => e.Id)
            .HasConversion(
                id => id.Value,
                value => EpicId.From(value))
            .IsRequired()
            .ValueGeneratedNever();

        // TenantId (required for multi-tenancy)
        builder.Property(e => e.TenantId)
            .HasConversion(
                id => id.Value,
                value => TenantId.From(value))
            .IsRequired()
            .HasColumnName("tenant_id");

        // ProjectId (foreign key)
        builder.Property(e => e.ProjectId)
            .HasConversion(
                id => id.Value,
                value => ProjectId.From(value))
            .IsRequired();

        // Basic properties
        builder.Property(e => e.Name)
            .HasMaxLength(200)
            .IsRequired();

        builder.Property(e => e.Description)
            .HasMaxLength(2000);

        // Status enumeration
        builder.Property(e => e.Status)
            .HasConversion(
                s => s.Name,
                name => Enumeration.FromDisplayName<WorkItemStatus>(name))
            .HasMaxLength(50)
            .IsRequired();

        // Priority enumeration
        builder.Property(e => e.Priority)
            .HasConversion(
                p => p.Name,
                name => Enumeration.FromDisplayName<TaskPriority>(name))
            .HasMaxLength(50)
            .IsRequired();

        // CreatedBy conversion
        builder.Property(e => e.CreatedBy)
            .HasConversion(
                id => id.Value,
                value => UserId.From(value))
            .IsRequired();

        // Timestamps
        builder.Property(e => e.CreatedAt)
            .IsRequired();

        builder.Property(e => e.UpdatedAt);

        // Configure Stories collection (owned by Epic in the aggregate)
        // Use string-based FK name because EpicId is a value object with conversion configured in StoryConfiguration
        builder.HasMany<Story>("Stories")
            .WithOne()
            .HasForeignKey("EpicId")
            .OnDelete(DeleteBehavior.Cascade);

        // Indexes
        builder.HasIndex(e => e.TenantId)
            .HasDatabaseName("ix_epics_tenant_id");
        builder.HasIndex(e => e.ProjectId);
        builder.HasIndex(e => e.CreatedAt);
    }
}
