using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using SolutionErp.Domain.Contracts;

namespace SolutionErp.Infrastructure.Persistence.Configurations;

public class WorkflowDefinitionConfiguration : IEntityTypeConfiguration<WorkflowDefinition>
{
    public void Configure(EntityTypeBuilder<WorkflowDefinition> e)
    {
        e.ToTable("WorkflowDefinitions");
        e.Property(x => x.Code).HasMaxLength(100).IsRequired();
        e.Property(x => x.Name).HasMaxLength(200).IsRequired();
        e.Property(x => x.Description).HasMaxLength(1000);
        e.Property(x => x.ContractType).HasConversion<int>();

        // Unique (Code, Version) — prevents duplicate version numbers per code
        e.HasIndex(x => new { x.Code, x.Version }).IsUnique();
        // Helper index — "get active by type" hot path
        e.HasIndex(x => new { x.ContractType, x.IsActive });
    }
}

public class WorkflowStepConfiguration : IEntityTypeConfiguration<WorkflowStep>
{
    public void Configure(EntityTypeBuilder<WorkflowStep> e)
    {
        e.ToTable("WorkflowSteps");
        e.Property(x => x.Name).HasMaxLength(200).IsRequired();
        e.Property(x => x.Phase).HasConversion<int>();
        e.Property(x => x.PositionLevel).HasConversion<int?>();   // Mig 21

        e.HasOne(x => x.WorkflowDefinition)
            .WithMany(d => d.Steps)
            .HasForeignKey(x => x.WorkflowDefinitionId)
            .OnDelete(DeleteBehavior.Cascade);

        // Mig 21 — FK Department Restrict (không xóa dept nếu còn step assigned).
        e.HasOne<SolutionErp.Domain.Master.Department>()
            .WithMany()
            .HasForeignKey(x => x.DepartmentId)
            .OnDelete(DeleteBehavior.Restrict);

        e.HasIndex(x => new { x.WorkflowDefinitionId, x.Order });
        e.HasIndex(x => x.DepartmentId);
    }
}

public class WorkflowStepApproverConfiguration : IEntityTypeConfiguration<WorkflowStepApprover>
{
    public void Configure(EntityTypeBuilder<WorkflowStepApprover> e)
    {
        e.ToTable("WorkflowStepApprovers");
        e.Property(x => x.Kind).HasConversion<int>();
        e.Property(x => x.AssignmentValue).HasMaxLength(100).IsRequired();

        e.HasOne(x => x.Step)
            .WithMany(s => s.Approvers)
            .HasForeignKey(x => x.WorkflowStepId)
            .OnDelete(DeleteBehavior.Cascade);
    }
}
