using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ColaFlow.Modules.IssueManagement.Domain.Entities;
using ColaFlow.Modules.IssueManagement.Domain.Enums;

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

/// <summary>
/// EF Core configuration for Issue entity
/// </summary>
public sealed class IssueConfiguration : IEntityTypeConfiguration<Issue>
{
    public void Configure(EntityTypeBuilder<Issue> builder)
    {
        builder.ToTable("Issues", "issue_management");

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

        builder.Property(i => i.Id)
            .ValueGeneratedNever(); // We generate Guid in domain

        builder.Property(i => i.TenantId)
            .IsRequired();

        builder.Property(i => i.ProjectId)
            .IsRequired();

        builder.Property(i => i.Title)
            .IsRequired()
            .HasMaxLength(200);

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

        // Enum to string conversions
        builder.Property(i => i.Type)
            .HasConversion<string>()
            .IsRequired()
            .HasMaxLength(50);

        builder.Property(i => i.Status)
            .HasConversion<string>()
            .IsRequired()
            .HasMaxLength(50);

        builder.Property(i => i.Priority)
            .HasConversion<string>()
            .IsRequired()
            .HasMaxLength(50);

        builder.Property(i => i.AssigneeId)
            .IsRequired(false);

        builder.Property(i => i.ReporterId)
            .IsRequired();

        builder.Property(i => i.CreatedAt)
            .IsRequired();

        builder.Property(i => i.UpdatedAt)
            .IsRequired(false);

        // Indexes for query performance
        builder.HasIndex(i => i.TenantId)
            .HasDatabaseName("IX_Issues_TenantId");

        builder.HasIndex(i => i.ProjectId)
            .HasDatabaseName("IX_Issues_ProjectId");

        builder.HasIndex(i => new { i.ProjectId, i.Status })
            .HasDatabaseName("IX_Issues_ProjectId_Status");

        builder.HasIndex(i => i.AssigneeId)
            .HasDatabaseName("IX_Issues_AssigneeId");

        builder.HasIndex(i => i.CreatedAt)
            .HasDatabaseName("IX_Issues_CreatedAt");

        // Ignore domain events (not persisted)
        builder.Ignore(i => i.DomainEvents);
    }
}
