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

namespace SolutionErp.Infrastructure.Persistence.Configurations;

// EF Mig 26 — UPSERT auto sync từ ApproveV2Async. UNIQUE (PEId, LevelId)
// đảm bảo 1 row/level/phiếu. FK Cascade Pe (xoá phiếu → xoá opinions),
// FK Restrict Level (admin xoá Level chặn nếu opinion tồn tại — bảo vệ data).
// SignedByUserId KHÔNG nav (tránh cascade khi xoá user; denorm SignedByFullName).
public class PurchaseEvaluationLevelOpinionConfiguration : IEntityTypeConfiguration<PurchaseEvaluationLevelOpinion>
{
    public void Configure(EntityTypeBuilder<PurchaseEvaluationLevelOpinion> e)
    {
        e.ToTable("PurchaseEvaluationLevelOpinions");

        e.Property(x => x.Comment).HasMaxLength(2000);
        e.Property(x => x.SignedByFullName).HasMaxLength(200).IsRequired();

        e.HasOne(x => x.PurchaseEvaluation)
            .WithMany(p => p.LevelOpinions)
            .HasForeignKey(x => x.PurchaseEvaluationId)
            .OnDelete(DeleteBehavior.Cascade);

        e.HasOne(x => x.Level)
            .WithMany()
            .HasForeignKey(x => x.ApprovalWorkflowLevelId)
            .OnDelete(DeleteBehavior.Restrict);

        e.HasIndex(x => new { x.PurchaseEvaluationId, x.ApprovalWorkflowLevelId }).IsUnique();
        e.HasIndex(x => x.ApprovalWorkflowLevelId);
    }
}
