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

namespace SolutionErp.Infrastructure.Persistence.Configurations;

// 2 bảng *DepartmentApprovals (Phase 9 — Migration 16) — 2-stage approval per
// phase × phòng ban cho HĐ / PE. (Budget variant XÓA cùng module Budget cũ —
// S61 Mig 50.)
//
// UNIQUE (TargetId, PhaseAtApproval, DepartmentId, Stage) — 1 phase × 1 phòng
// × 1 stage = 1 row duy nhất. UPDATE in-place khi user đổi ý → audit qua
// *Changelog.
//
// FK Cascade theo target (xóa HĐ/PE → xóa approval rows).

public class ContractDepartmentApprovalConfiguration
    : IEntityTypeConfiguration<ContractDepartmentApproval>
{
    public void Configure(EntityTypeBuilder<ContractDepartmentApproval> b)
    {
        b.ToTable("ContractDepartmentApprovals");
        b.HasKey(x => x.Id);

        b.Property(x => x.Stage).HasConversion<int>();
        b.Property(x => x.ApproverRoleSnapshot).HasMaxLength(100);
        b.Property(x => x.Comment).HasMaxLength(1000);

        // Mig 21 — drop InnerStepId column + restore simple unique non-filtered.
        b.HasIndex(x => new { x.ContractId, x.PhaseAtApproval, x.DepartmentId, x.Stage })
            .IsUnique()
            .HasDatabaseName("UX_ContractDeptApprovals_Contract_Phase_Dept_Stage");

        b.HasIndex(x => x.ContractId);
        b.HasIndex(x => x.DepartmentId);
        b.HasIndex(x => x.ApproverUserId);

        b.HasOne(x => x.Contract)
            .WithMany(c => c.DepartmentApprovals)
            .HasForeignKey(x => x.ContractId)
            .OnDelete(DeleteBehavior.Cascade);
    }
}

public class PurchaseEvaluationDepartmentApprovalConfiguration
    : IEntityTypeConfiguration<PurchaseEvaluationDepartmentApproval>
{
    public void Configure(EntityTypeBuilder<PurchaseEvaluationDepartmentApproval> b)
    {
        b.ToTable("PurchaseEvaluationDepartmentApprovals");
        b.HasKey(x => x.Id);

        b.Property(x => x.Stage).HasConversion<int>();
        b.Property(x => x.ApproverRoleSnapshot).HasMaxLength(100);
        b.Property(x => x.Comment).HasMaxLength(1000);

        // Mig 21 — drop InnerStepId column + restore simple unique non-filtered.
        b.HasIndex(x => new { x.PurchaseEvaluationId, x.PhaseAtApproval, x.DepartmentId, x.Stage })
            .IsUnique()
            .HasDatabaseName("UX_PEDeptApprovals_PE_Phase_Dept_Stage");

        b.HasIndex(x => x.PurchaseEvaluationId);
        b.HasIndex(x => x.DepartmentId);
        b.HasIndex(x => x.ApproverUserId);

        b.HasOne(x => x.PurchaseEvaluation)
            .WithMany(c => c.DepartmentApprovals)
            .HasForeignKey(x => x.PurchaseEvaluationId)
            .OnDelete(DeleteBehavior.Cascade);
    }
}
