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

namespace SolutionErp.Infrastructure.Persistence.Configurations;

// Plan B Chunk C (S29 — Mig 33, 2026-05-22) — cookie-cutter mirror
// PurchaseEvaluationLevelOpinionConfiguration (Mig 26 S19).
//
// UPSERT auto sync từ ContractWorkflowService.ApproveV2Async (Plan B Chunk D em
// main wire). UNIQUE (ContractId, ApprovalWorkflowLevelId) đảm bảo 1 row/level/HĐ.
// FK Cascade Contract (xoá HĐ → 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 ContractLevelOpinionConfiguration : IEntityTypeConfiguration<ContractLevelOpinion>
{
    public void Configure(EntityTypeBuilder<ContractLevelOpinion> e)
    {
        e.ToTable("ContractLevelOpinions");

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

        e.HasOne(x => x.Contract)
            .WithMany(c => c.LevelOpinions)
            .HasForeignKey(x => x.ContractId)
            .OnDelete(DeleteBehavior.Cascade);

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

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