using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Tiku.Domain.Identity;
using Tiku.Domain.Operations;
using Tiku.Domain.Platform;
using Tiku.Domain.Tenancy;

namespace Tiku.Infrastructure.Persistence.Configurations;

internal sealed class PlatformSaasPlanConfiguration : IEntityTypeConfiguration<PlatformSaasPlan>
{
    public void Configure(EntityTypeBuilder<PlatformSaasPlan> builder)
    {
        builder.ConfigureEntity("platform_saas_plans");
        builder.ConfigureTimestamps();
        builder.Property(entity => entity.Code).HasMaxLength(100);
        builder.Property(entity => entity.Name).HasMaxLength(200);
        builder.Property(entity => entity.BillingCycle).HasSnakeCaseEnum();
        builder.Property(entity => entity.Currency).HasMaxLength(10);
        builder.Property(entity => entity.IncludedQuotas).IsJson("{}");
        builder.Property(entity => entity.OveragePrices).IsJson("{}");
        builder.Property(entity => entity.FeatureFlags).IsJson("{}");
        builder.Property(entity => entity.Status).HasSnakeCaseEnum();
        builder.HasIndex(entity => entity.Code).IsUnique();
        builder.HasIndex(entity => new { entity.Status, entity.SortOrder });
        builder.ToTable(table => table.HasCheckConstraint("ck_platform_saas_plans_amount", "base_amount_cents >= 0"));
    }
}

internal sealed class TenantBillingProfileConfiguration : IEntityTypeConfiguration<TenantBillingProfile>
{
    public void Configure(EntityTypeBuilder<TenantBillingProfile> builder)
    {
        builder.ToTable("tenant_billing_profiles");
        builder.HasKey(entity => entity.TenantId);
        builder.ConfigureTimestamps();
        builder.Property(entity => entity.BillingName).HasMaxLength(300);
        builder.Property(entity => entity.TaxId).HasMaxLength(100);
        builder.Property(entity => entity.ContactName).HasMaxLength(100);
        builder.Property(entity => entity.ContactPhone).HasMaxLength(50);
        builder.Property(entity => entity.ContactEmail).HasColumnType("citext").HasMaxLength(300);
        builder.Property(entity => entity.InvoiceTitle).HasMaxLength(300);
        builder.Property(entity => entity.InvoiceType).HasNullableSnakeCaseEnum();
        builder.Property(entity => entity.BankName).HasMaxLength(200);
        builder.Property(entity => entity.BankAccountMasked).HasMaxLength(100);
        builder.Property(entity => entity.Metadata).IsJson("{}");
        builder.HasOne<Tenant>().WithOne().HasForeignKey<TenantBillingProfile>(entity => entity.TenantId).OnDelete(DeleteBehavior.Cascade);
    }
}

internal sealed class TenantInvoiceConfiguration : IEntityTypeConfiguration<TenantInvoice>
{
    public void Configure(EntityTypeBuilder<TenantInvoice> builder)
    {
        builder.ConfigureTenantEntity("tenant_invoices");
        builder.ConfigureTimestamps();
        builder.Property(entity => entity.InvoiceNo).HasMaxLength(100);
        builder.Property(entity => entity.InvoiceType).HasSnakeCaseEnum();
        builder.Property(entity => entity.Status).HasSnakeCaseEnum();
        builder.Property(entity => entity.Currency).HasMaxLength(10);
        builder.Property(entity => entity.Metadata).IsJson("{}");
        builder.HasIndex(entity => new { entity.TenantId, entity.InvoiceNo }).IsUnique();
        builder.HasIndex(entity => new { entity.TenantId, entity.Status, entity.DueDate });
        builder.HasIndex(entity => new { entity.TenantId, entity.BillingPeriodStart, entity.BillingPeriodEnd })
            .IsUnique()
            .HasFilter("invoice_type = 'usage_overage' and status <> 'void' and metadata->>'source' = 'usage_overage_auto'");
        builder.ToTable(table =>
        {
            table.HasCheckConstraint("ck_tenant_invoices_amounts", "subtotal_cents >= 0 and discount_cents >= 0 and tax_cents >= 0 and total_cents >= 0 and paid_cents >= 0 and balance_cents >= 0");
            table.HasCheckConstraint("ck_tenant_invoices_period", "billing_period_end is null or billing_period_start is null or billing_period_end >= billing_period_start");
        });
        builder.HasOne<User>().WithMany().HasForeignKey(entity => entity.CreatedBy).OnDelete(DeleteBehavior.SetNull);
    }
}

internal sealed class TenantInvoiceItemConfiguration : IEntityTypeConfiguration<TenantInvoiceItem>
{
    public void Configure(EntityTypeBuilder<TenantInvoiceItem> builder)
    {
        builder.ConfigureEntity("tenant_invoice_items");
        builder.HasAlternateKey(entity => new { entity.TenantId, entity.Id });
        builder.Property(entity => entity.ItemType).HasMaxLength(100);
        builder.Property(entity => entity.Description).HasMaxLength(500);
        builder.Property(entity => entity.Quantity).HasPrecision(12, 2);
        builder.Property(entity => entity.Metadata).IsJson("{}");
        builder.Property(entity => entity.CreatedAt).HasDefaultValueSql("now()");
        builder.HasIndex(entity => entity.InvoiceId);
        builder.ToTable(table =>
        {
            table.HasCheckConstraint("ck_tenant_invoice_items_quantity", "quantity > 0");
            table.HasCheckConstraint("ck_tenant_invoice_items_amounts", "unit_amount_cents >= 0 and amount_cents >= 0");
        });
        builder.HasOne<Tenant>().WithMany().HasForeignKey(entity => entity.TenantId).OnDelete(DeleteBehavior.Cascade);
        builder.HasOne<TenantInvoice>().WithMany()
            .HasForeignKey(entity => new { entity.TenantId, entity.InvoiceId })
            .HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
            .OnDelete(DeleteBehavior.Cascade);
    }
}

internal sealed class TenantInvoicePaymentConfiguration : IEntityTypeConfiguration<TenantInvoicePayment>
{
    public void Configure(EntityTypeBuilder<TenantInvoicePayment> builder)
    {
        builder.ConfigureTenantEntity("tenant_invoice_payments");
        builder.ConfigureTimestamps();
        builder.Property(entity => entity.PaymentNo).HasMaxLength(100);
        builder.Property(entity => entity.Provider).HasMaxLength(50);
        builder.Property(entity => entity.Method).HasMaxLength(50);
        builder.Property(entity => entity.Status).HasSnakeCaseEnum();
        builder.Property(entity => entity.ProviderTradeNo).HasMaxLength(200);
        builder.Property(entity => entity.RawPayload).IsJson("{}");
        builder.HasIndex(entity => new { entity.TenantId, entity.PaymentNo }).IsUnique();
        builder.HasIndex(entity => new { entity.InvoiceId, entity.Status });
        builder.ToTable(table => table.HasCheckConstraint("ck_tenant_invoice_payments_amount", "amount_cents >= 0"));
        builder.HasOne<TenantInvoice>().WithMany()
            .HasForeignKey(entity => new { entity.TenantId, entity.InvoiceId })
            .HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
            .OnDelete(DeleteBehavior.Cascade);
        builder.HasOne<User>().WithMany().HasForeignKey(entity => entity.ReceivedBy).OnDelete(DeleteBehavior.SetNull);
    }
}

internal sealed class TenantInvoiceReminderConfiguration : IEntityTypeConfiguration<TenantInvoiceReminder>
{
    public void Configure(EntityTypeBuilder<TenantInvoiceReminder> builder)
    {
        builder.ConfigureTenantEntity("tenant_invoice_reminders");
        builder.ConfigureTimestamps();
        builder.Property(entity => entity.ReminderType).HasSnakeCaseEnum();
        builder.Property(entity => entity.Channel).HasSnakeCaseEnum();
        builder.Property(entity => entity.Status).HasSnakeCaseEnum();
        builder.Property(entity => entity.Metadata).IsJson("{}");
        builder.HasIndex(entity => new { entity.TenantId, entity.InvoiceId, entity.ReminderType, entity.Channel, entity.ReminderDate }).IsUnique();
        builder.HasIndex(entity => new { entity.TenantId, entity.Status, entity.ReminderDate });
        builder.HasIndex(entity => new { entity.InvoiceId, entity.ReminderDate });
        builder.ToTable(table =>
        {
            table.HasCheckConstraint("ck_tenant_invoice_reminders_level", "reminder_level between 1 and 20");
            table.HasCheckConstraint("ck_tenant_invoice_reminders_balance", "balance_cents_snapshot >= 0");
        });
        builder.HasOne<TenantInvoice>().WithMany()
            .HasForeignKey(entity => new { entity.TenantId, entity.InvoiceId })
            .HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
            .OnDelete(DeleteBehavior.Cascade);
        builder.HasOne<User>().WithMany().HasForeignKey(entity => entity.CreatedBy).OnDelete(DeleteBehavior.SetNull);
    }
}

internal sealed class PlatformAuditAlertRuleConfiguration : IEntityTypeConfiguration<PlatformAuditAlertRule>
{
    public void Configure(EntityTypeBuilder<PlatformAuditAlertRule> builder)
    {
        builder.ConfigureEntity("platform_audit_alert_rules");
        builder.ConfigureTimestamps();
        builder.Property(entity => entity.Code).HasMaxLength(100);
        builder.Property(entity => entity.Name).HasMaxLength(200);
        builder.Property(entity => entity.Severity).HasSnakeCaseEnum();
        builder.Property(entity => entity.ActionPatterns).HasColumnType("text[]").HasDefaultValueSql("'{}'::text[]");
        builder.Property(entity => entity.TargetTypes).HasColumnType("text[]").HasDefaultValueSql("'{}'::text[]");
        builder.Property(entity => entity.Conditions).IsJson("{}");
        builder.Property(entity => entity.Metadata).IsJson("{}");
        builder.HasIndex(entity => entity.Code).IsUnique();
        builder.HasIndex(entity => new { entity.Enabled, entity.Severity, entity.Code });
        builder.HasOne<Tenant>().WithMany().HasForeignKey(entity => entity.TenantId).OnDelete(DeleteBehavior.Cascade);
    }
}

internal sealed class PlatformAuditAlertConfiguration : IEntityTypeConfiguration<PlatformAuditAlert>
{
    public void Configure(EntityTypeBuilder<PlatformAuditAlert> builder)
    {
        builder.ConfigureEntity("platform_audit_alerts");
        builder.ConfigureTimestamps();
        builder.Property(entity => entity.Severity).HasSnakeCaseEnum();
        builder.Property(entity => entity.Status).HasSnakeCaseEnum();
        builder.Property(entity => entity.Action).HasMaxLength(200);
        builder.Property(entity => entity.TargetType).HasMaxLength(200);
        builder.Property(entity => entity.TargetId).HasMaxLength(200);
        builder.Property(entity => entity.Title).HasMaxLength(300);
        builder.Property(entity => entity.Details).IsJson("{}");
        builder.Property(entity => entity.FirstSeenAt).HasDefaultValueSql("now()");
        builder.Property(entity => entity.LastSeenAt).HasDefaultValueSql("now()");
        builder.HasIndex(entity => new { entity.RuleId, entity.AuditLogId }).IsUnique();
        builder.HasIndex(entity => new { entity.Status, entity.Severity, entity.CreatedAt });
        builder.HasIndex(entity => new { entity.TenantId, entity.Status, entity.CreatedAt });
        builder.HasIndex(entity => entity.AuditLogId);
        builder.HasOne<PlatformAuditAlertRule>().WithMany().HasForeignKey(entity => entity.RuleId).OnDelete(DeleteBehavior.Cascade);
        builder.HasOne<AuditLog>().WithMany().HasForeignKey(entity => entity.AuditLogId).OnDelete(DeleteBehavior.Cascade);
        builder.HasOne<Tenant>().WithMany().HasForeignKey(entity => entity.TenantId).OnDelete(DeleteBehavior.Cascade);
        builder.HasOne<User>().WithMany().HasForeignKey(entity => entity.AcknowledgedBy).OnDelete(DeleteBehavior.SetNull);
        builder.HasOne<User>().WithMany().HasForeignKey(entity => entity.ResolvedBy).OnDelete(DeleteBehavior.SetNull);
    }
}

internal sealed class PlatformDunningNotificationChannelConfiguration : IEntityTypeConfiguration<PlatformDunningNotificationChannel>
{
    public void Configure(EntityTypeBuilder<PlatformDunningNotificationChannel> builder)
    {
        builder.ConfigureEntity("platform_dunning_notification_channels");
        builder.ConfigureTimestamps();
        builder.Property(entity => entity.ChannelCode).HasMaxLength(100);
        builder.Property(entity => entity.Name).HasMaxLength(200);
        builder.Property(entity => entity.Provider).HasSnakeCaseEnum();
        builder.Property(entity => entity.WebhookUrl).HasMaxLength(2048);
        builder.Property(entity => entity.SecretRef).HasMaxLength(300);
        builder.Property(entity => entity.ReminderTypes).HasColumnType("text[]").HasDefaultValueSql("array['overdue', 'final_notice']::text[]");
        builder.Property(entity => entity.ReminderChannels).HasColumnType("text[]").HasDefaultValueSql("array['internal']::text[]");
        builder.Property(entity => entity.TenantIds).HasColumnType("uuid[]").HasDefaultValueSql("'{}'::uuid[]");
        builder.Property(entity => entity.Metadata).IsJson("{}");
        builder.HasIndex(entity => entity.ChannelCode).IsUnique();
        builder.HasIndex(entity => new { entity.Enabled, entity.MinReminderLevel, entity.ChannelCode });
        builder.ToTable(table =>
        {
            table.HasCheckConstraint("ck_platform_dunning_channels_level", "min_reminder_level between 1 and 20");
            table.HasCheckConstraint("ck_platform_dunning_channels_timeout", "timeout_seconds between 1 and 60");
        });
    }
}

internal sealed class PlatformDunningNotificationEventConfiguration : IEntityTypeConfiguration<PlatformDunningNotificationEvent>
{
    public void Configure(EntityTypeBuilder<PlatformDunningNotificationEvent> builder)
    {
        builder.ConfigureTenantEntity("platform_dunning_notification_events");
        builder.ConfigureTimestamps();
        builder.Property(entity => entity.Provider).HasSnakeCaseEnum();
        builder.Property(entity => entity.Status).HasSnakeCaseEnum();
        builder.Property(entity => entity.RequestPayload).IsJson("{}");
        builder.Property(entity => entity.Metadata).IsJson("{}");
        builder.Property(entity => entity.ScheduledAt).HasDefaultValueSql("now()");
        builder.HasIndex(entity => new { entity.TenantId, entity.ChannelId, entity.ReminderId }).IsUnique();
        builder.HasIndex(entity => new { entity.Status, entity.NextAttemptAt, entity.ScheduledAt, entity.CreatedAt });
        builder.HasIndex(entity => new { entity.ReminderId, entity.Status, entity.CreatedAt });
        builder.HasIndex(entity => new { entity.InvoiceId, entity.Status, entity.CreatedAt });
        builder.HasIndex(entity => new { entity.TenantId, entity.Status, entity.CreatedAt });
        builder.ToTable(table => table.HasCheckConstraint("ck_platform_dunning_events_attempts", "attempts >= 0"));
        builder.HasOne<PlatformDunningNotificationChannel>().WithMany().HasForeignKey(entity => entity.ChannelId).OnDelete(DeleteBehavior.Cascade);
        builder.HasOne<TenantInvoiceReminder>().WithMany()
            .HasForeignKey(entity => new { entity.TenantId, entity.ReminderId })
            .HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
            .OnDelete(DeleteBehavior.Cascade);
        builder.HasOne<TenantInvoice>().WithMany()
            .HasForeignKey(entity => new { entity.TenantId, entity.InvoiceId })
            .HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
            .OnDelete(DeleteBehavior.Cascade);
    }
}
