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

namespace ERPCore.Infra.Persistence.Configurations;

public sealed class EmployeeLoanConfiguration : IEntityTypeConfiguration<EmployeeLoan>
{
    public void Configure(EntityTypeBuilder<EmployeeLoan> builder)
    {
        builder.ToTable("hr_employee_loans");
        builder.HasKey(l => l.EmployeeLoanId);

        builder.Property(l => l.DocNo).IsRequired().HasMaxLength(30);
        builder.HasIndex(l => l.DocNo).IsUnique();
        builder.Property(l => l.LoanKind).HasConversion<string>().HasMaxLength(20).IsRequired();
        builder.Property(l => l.Status).HasConversion<string>().HasMaxLength(20).IsRequired();

        builder.Property(l => l.PrincipalAmount).HasPrecision(18, 2);
        builder.Property(l => l.InterestRate).HasPrecision(6, 4);
        builder.Property(l => l.InstallmentAmount).HasPrecision(18, 2);
        builder.Property(l => l.OutstandingBalance).HasPrecision(18, 2);

        builder.HasOne(l => l.Employee).WithMany()
            .HasForeignKey(l => l.EmployeeId).OnDelete(DeleteBehavior.Restrict);

        builder.HasMany(l => l.Installments).WithOne(i => i.EmployeeLoan!)
            .HasForeignKey(i => i.EmployeeLoanId).OnDelete(DeleteBehavior.Cascade);

        builder.Property(l => l.CreatedAt).IsRequired();
        builder.Property(l => l.RowVersion).IsRowVersion();

        builder.HasIndex(l => l.EmployeeId);
        builder.HasIndex(l => l.Status);
    }
}

public sealed class LoanInstallmentConfiguration : IEntityTypeConfiguration<LoanInstallment>
{
    public void Configure(EntityTypeBuilder<LoanInstallment> builder)
    {
        builder.ToTable("hr_loan_installments");
        builder.HasKey(i => i.LoanInstallmentId);

        builder.Property(i => i.ScheduledAmount).HasPrecision(18, 2);
        builder.Property(i => i.PaidAmount).HasPrecision(18, 2);
        builder.Property(i => i.Status).HasConversion<string>().HasMaxLength(20).IsRequired();

        builder.HasOne(i => i.PayrollRun).WithMany()
            .HasForeignKey(i => i.PayrollRunId).OnDelete(DeleteBehavior.Restrict);

        builder.Property(i => i.RowVersion).IsRowVersion();

        builder.HasIndex(i => new { i.DueYear, i.DueMonth });
    }
}
