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

namespace ERPCore.Infra.Persistence.Configurations;

public sealed class AuditLogConfiguration : IEntityTypeConfiguration<AuditLog>
{
    public void Configure(EntityTypeBuilder<AuditLog> builder)
    {
        builder.ToTable("audit_logs");
        builder.HasKey(a => a.AuditId);

        builder.Property(a => a.EntityType).IsRequired().HasMaxLength(80);
        builder.Property(a => a.Action).HasConversion<string>().HasMaxLength(10).IsRequired();
        builder.Property(a => a.ChangeSet).IsRequired().HasColumnType("jsonb");
        builder.Property(a => a.CreatedAt).IsRequired();

        builder.HasOne<User>().WithMany().HasForeignKey(a => a.UserId).OnDelete(DeleteBehavior.Restrict);

        builder.HasIndex(a => new { a.EntityType, a.EntityId });
        builder.HasIndex(a => a.CreatedAt);
        builder.HasIndex(a => a.UserId);
    }
}

public sealed class JournalEntryStubConfiguration : IEntityTypeConfiguration<JournalEntryStub>
{
    public void Configure(EntityTypeBuilder<JournalEntryStub> builder)
    {
        builder.ToTable("journal_entry_stubs");
        builder.HasKey(j => j.JournalId);

        builder.Property(j => j.SourceDocType).IsRequired().HasMaxLength(10);
        builder.Property(j => j.DebitAccount).IsRequired().HasMaxLength(20);
        builder.Property(j => j.CreditAccount).IsRequired().HasMaxLength(20);
        builder.Property(j => j.Amount).HasPrecision(18, 4);

        builder.HasIndex(j => new { j.SourceDocType, j.SourceDocId });
    }
}
