using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using AdsBillingService.Domain.AggregatesModel.InvoiceAggregate;

namespace AdsBillingService.Infrastructure.EntityConfigurations;

/// <summary>
/// EN: Entity configuration for Invoice aggregate.
/// VI: Cấu hình entity cho aggregate Invoice.
/// </summary>
public class InvoiceEntityTypeConfiguration : IEntityTypeConfiguration<Invoice>
{
    public void Configure(EntityTypeBuilder<Invoice> builder)
    {
        // EN: Table name / VI: Tên bảng
        builder.ToTable("invoices");

        // EN: Primary key / VI: Khóa chính
        builder.HasKey(i => i.Id);
        builder.Property(i => i.Id)
            .HasColumnName("id")
            .IsRequired();

        // EN: Billing account ID / VI: ID tài khoản billing
        builder.Property(i => i.BillingAccountId)
            .HasColumnName("billing_account_id")
            .IsRequired();

        builder.HasIndex(i => i.BillingAccountId)
            .HasDatabaseName("ix_invoices_billing_account_id");

        // EN: Invoice number / VI: Số hóa đơn
        builder.Property(i => i.InvoiceNumber)
            .HasColumnName("invoice_number")
            .HasMaxLength(50)
            .IsRequired();

        builder.HasIndex(i => i.InvoiceNumber)
            .IsUnique()
            .HasDatabaseName("ix_invoices_invoice_number");

        // EN: Status / VI: Trạng thái
        builder.Property(i => i.Status)
            .HasColumnName("status")
            .HasConversion<int>()
            .IsRequired();

        builder.HasIndex(i => i.Status)
            .HasDatabaseName("ix_invoices_status");

        // EN: Issue date / VI: Ngày phát hành
        builder.Property(i => i.IssueDate)
            .HasColumnName("issue_date")
            .IsRequired();

        // EN: Due date / VI: Ngày đến hạn
        builder.Property(i => i.DueDate)
            .HasColumnName("due_date")
            .IsRequired();

        builder.HasIndex(i => i.DueDate)
            .HasDatabaseName("ix_invoices_due_date");

        // EN: Total amount / VI: Tổng tiền
        builder.Property(i => i.TotalAmount)
            .HasColumnName("total_amount")
            .HasColumnType("decimal(18,2)")
            .IsRequired();

        // EN: Line items as owned collection via navigation property
        // VI: Các dòng chi tiết qua navigation property
        // NOTE: Must use the navigation expression to avoid EF creating a shadow InvoiceId1 FK
        var navigation = builder.Metadata.FindNavigation(nameof(Invoice.LineItems))!;
        navigation.SetPropertyAccessMode(PropertyAccessMode.Field);

        builder.HasMany(i => i.LineItems)
            .WithOne()
            .HasForeignKey("InvoiceId")
            .OnDelete(DeleteBehavior.Cascade);
    }
}
