using ERPCore.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace ERPCore.Infra.Persistence.Configurations;

public sealed class PayrollRunConfiguration : IEntityTypeConfiguration<PayrollRun>
{
    public void Configure(EntityTypeBuilder<PayrollRun> builder)
    {
        builder.ToTable("hr_payroll_runs");
        builder.HasKey(r => r.PayrollRunId);

        builder.Property(r => r.DocNo).IsRequired().HasMaxLength(30);
        builder.HasIndex(r => r.DocNo).IsUnique();
        builder.Property(r => r.Status).HasConversion<string>().HasMaxLength(20).IsRequired();
        builder.Property(r => r.UnlockReason).HasMaxLength(500);

        builder.HasOne(r => r.Branch).WithMany()
            .HasForeignKey(r => r.BranchId).OnDelete(DeleteBehavior.Restrict);

        builder.HasMany(r => r.Lines).WithOne(l => l.PayrollRun!)
            .HasForeignKey(l => l.PayrollRunId).OnDelete(DeleteBehavior.Cascade);

        builder.Property(r => r.GeneratedAt).IsRequired();
        builder.Property(r => r.RowVersion).IsRowVersion();

        builder.HasIndex(r => new { r.PeriodYear, r.PeriodMonth, r.BranchId });
        builder.HasIndex(r => r.Status);
    }
}
