using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using TakeoutSaaS.Domain.Tenants.Entities;

namespace TakeoutSaaS.Infrastructure.App.Persistence.Configurations;

/// <summary>
/// <see cref="TenantPayment"/> EF Core 映射配置。
/// </summary>
public sealed class TenantPaymentConfiguration : IEntityTypeConfiguration<TenantPayment>
{
    /// <inheritdoc />
    public void Configure(EntityTypeBuilder<TenantPayment> builder)
    {
        builder.ToTable("tenant_payments");
        builder.HasKey(x => x.Id);

        // 1. 字段约束
        builder.Property(x => x.BillingStatementId).IsRequired();
        builder.Property(x => x.Amount).HasPrecision(18, 2).IsRequired();
        builder.Property(x => x.Method).HasConversion<int>();
        builder.Property(x => x.Status).HasConversion<int>();
        builder.Property(x => x.TransactionNo).HasMaxLength(64);
        builder.Property(x => x.ProofUrl).HasMaxLength(512);
        builder.Property(x => x.RefundReason).HasMaxLength(512);
        builder.Property(x => x.Notes).HasMaxLength(512);

        // 2. 复合索引：租户+账单
        builder.HasIndex(x => new { x.TenantId, x.BillingStatementId });

        // 3. 支付记录时间排序索引
        builder.HasIndex(x => new { x.BillingStatementId, x.PaidAt })
            .HasDatabaseName("idx_payment_billing_paidat");

        // 4. 交易号索引（部分索引：仅非空）
        builder.HasIndex(x => x.TransactionNo)
            .HasDatabaseName("idx_payment_transaction_no")
            .HasFilter("\"TransactionNo\" IS NOT NULL");
    }
}
