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 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 TenantBillingPolicyConfiguration : IEntityTypeConfiguration<TenantBillingPolicy>
{
    public void Configure(EntityTypeBuilder<TenantBillingPolicy> builder)
    {
        builder.ToTable("tenant_billing_policies");
        builder.HasKey(entity => entity.TenantId);
        builder.ConfigureTimestamps();
        builder.Property(entity => entity.CollectionMode).HasSnakeCaseEnum();
        builder.Property(entity => entity.DefaultPaymentProvider).HasMaxLength(50);
        builder.ToTable(table => table.HasCheckConstraint(
            "ck_tenant_billing_policies_renewal_lead_days",
            "renewal_lead_days between 1 and 90"));
        builder.HasOne<Tenant>().WithOne().HasForeignKey<TenantBillingPolicy>(entity => entity.TenantId)
            .OnDelete(DeleteBehavior.Cascade);
    }
}

internal sealed class TenantOwnerActivationGrantConfiguration : IEntityTypeConfiguration<TenantOwnerActivationGrant>
{
    public void Configure(EntityTypeBuilder<TenantOwnerActivationGrant> builder)
    {
        builder.ConfigureTenantEntity("tenant_owner_activation_grants");
        builder.ConfigureTimestamps();
        builder.Property(entity => entity.TokenHash).HasMaxLength(64);
        builder.Property(entity => entity.RevocationReason).HasMaxLength(1000);
        builder.HasIndex(entity => new { entity.TenantId, entity.UserId, entity.ConsumedAt, entity.ExpiresAt });
        builder.HasIndex(entity => entity.TokenHash).IsUnique().HasAnnotation("Tiku:GlobalUnique", true);
        builder.HasIndex(entity => new { entity.TenantId, entity.UserId })
            .IsUnique()
            .HasFilter("consumed_at is null and revoked_at is null");
        builder.HasOne<User>().WithMany().HasForeignKey(entity => entity.UserId).OnDelete(DeleteBehavior.Cascade);
        builder.HasOne<User>().WithMany().HasForeignKey(entity => entity.CreatedBy).OnDelete(DeleteBehavior.Restrict);
        builder.HasOne<TenantDomain>().WithMany().HasForeignKey(entity => new { entity.TenantId, entity.DomainId })
            .HasPrincipalKey(entity => new { entity.TenantId, entity.Id }).OnDelete(DeleteBehavior.Restrict);
        builder.HasOne<User>().WithMany().HasForeignKey(entity => entity.RevokedBy).OnDelete(DeleteBehavior.Restrict);
    }
}

internal sealed class PlatformOperationIdempotencyConfiguration : IEntityTypeConfiguration<PlatformOperationIdempotency>
{
    public void Configure(EntityTypeBuilder<PlatformOperationIdempotency> builder)
    {
        builder.ConfigureEntity("platform_operation_idempotencies");
        builder.ConfigureTimestamps();
        builder.Property(entity => entity.Scope).HasMaxLength(100);
        builder.Property(entity => entity.IdempotencyKey).HasMaxLength(200);
        builder.Property(entity => entity.RequestHash).HasMaxLength(64);
        builder.HasIndex(entity => new { entity.ActorUserId, entity.Scope, entity.IdempotencyKey }).IsUnique();
        builder.HasOne<User>().WithMany().HasForeignKey(entity => entity.ActorUserId).OnDelete(DeleteBehavior.Restrict);
    }
}

internal sealed class
    PlatformBillingInvoiceReminderConfiguration : IEntityTypeConfiguration<PlatformBillingInvoiceReminder>
{
    public void Configure(EntityTypeBuilder<PlatformBillingInvoiceReminder> builder)
    {
        builder.ConfigureTenantEntity("platform_billing_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_platform_billing_invoice_reminders_level", "reminder_level between 1 and 20");
            table.HasCheckConstraint("ck_platform_billing_invoice_reminders_balance", "balance_cents_snapshot >= 0");
        });
        builder.HasOne<PlatformBillingInvoice>().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
    PlatformBillingDunningNotificationChannelConfiguration : IEntityTypeConfiguration<
    PlatformBillingDunningNotificationChannel>
{
    public void Configure(EntityTypeBuilder<PlatformBillingDunningNotificationChannel> builder)
    {
        builder.ConfigureEntity("platform_billing_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_billing_dunning_channels_level",
                "min_reminder_level between 1 and 20");
            table.HasCheckConstraint("ck_platform_billing_dunning_channels_timeout",
                "timeout_seconds between 1 and 60");
        });
    }
}

internal sealed class
    PlatformBillingDunningNotificationEventConfiguration : IEntityTypeConfiguration<
    PlatformBillingDunningNotificationEvent>
{
    public void Configure(EntityTypeBuilder<PlatformBillingDunningNotificationEvent> builder)
    {
        builder.ConfigureTenantEntity("platform_billing_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_billing_dunning_events_attempts", "attempts >= 0"));
        builder.HasOne<PlatformBillingDunningNotificationChannel>().WithMany()
            .HasForeignKey(entity => entity.ChannelId)
            .HasConstraintName("fk_platform_billing_dunning_events_channel")
            .OnDelete(DeleteBehavior.Cascade);
        builder.HasOne<PlatformBillingInvoiceReminder>().WithMany()
            .HasForeignKey(entity => new { entity.TenantId, entity.ReminderId })
            .HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
            .HasConstraintName("fk_platform_billing_dunning_events_reminder")
            .OnDelete(DeleteBehavior.Cascade);
        builder.HasOne<PlatformBillingInvoice>().WithMany()
            .HasForeignKey(entity => new { entity.TenantId, entity.InvoiceId })
            .HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
            .HasConstraintName("fk_platform_billing_dunning_events_invoice")
            .OnDelete(DeleteBehavior.Cascade);
    }
}

internal sealed class PlatformPaymentAppConfiguration : IEntityTypeConfiguration<PlatformPaymentApp>
{
    public void Configure(EntityTypeBuilder<PlatformPaymentApp> builder)
    {
        builder.ConfigureEntity("platform_payment_apps");
        builder.ConfigureTimestamps();
        builder.Property(entity => entity.AppCode).HasMaxLength(100);
        builder.Property(entity => entity.AppName).HasMaxLength(200);
        builder.Property(entity => entity.Status).HasSnakeCaseEnum();
        builder.Property(entity => entity.SettlementMode).HasMaxLength(100);
        builder.Property(entity => entity.Description).HasMaxLength(500);
        builder.Property(entity => entity.Metadata).IsJson("{}");
        builder.HasIndex(entity => entity.AppCode).IsUnique();
        builder.HasIndex(entity => new { entity.Status, entity.AppCode });
    }
}

internal sealed class PlatformPaymentChannelConfiguration : IEntityTypeConfiguration<PlatformPaymentChannel>
{
    public void Configure(EntityTypeBuilder<PlatformPaymentChannel> builder)
    {
        builder.ConfigureEntity("platform_payment_channels");
        builder.ConfigureTimestamps();
        builder.Property(entity => entity.Provider).HasMaxLength(80);
        builder.Property(entity => entity.Mode).HasMaxLength(100);
        builder.Property(entity => entity.Status).HasSnakeCaseEnum();
        builder.Property(entity => entity.DisplayName).HasMaxLength(200);
        builder.Property(entity => entity.SecretRef).HasMaxLength(300);
        builder.Property(entity => entity.CallbackPath).HasMaxLength(500);
        builder.Property(entity => entity.ConfigPublic).IsJson("{}");
        builder.Property(entity => entity.Metadata).IsJson("{}");
        builder.HasIndex(entity => new { entity.AppId, entity.Provider }).IsUnique();
        builder.HasIndex(entity => new { entity.Status, entity.Priority, entity.Provider });
        builder.HasOne<PlatformPaymentApp>().WithMany().HasForeignKey(entity => entity.AppId)
            .OnDelete(DeleteBehavior.Cascade);
    }
}

internal sealed class PlatformApprovalPolicyConfiguration : IEntityTypeConfiguration<PlatformApprovalPolicy>
{
    public void Configure(EntityTypeBuilder<PlatformApprovalPolicy> builder)
    {
        builder.ConfigureEntity("platform_approval_policies");
        builder.ConfigureTimestamps();
        builder.Property(entity => entity.Code).HasMaxLength(120);
        builder.Property(entity => entity.Name).HasMaxLength(200);
        builder.Property(entity => entity.RequiredPermission).HasMaxLength(200);
        builder.Property(entity => entity.Conditions).IsJson("{}");
        builder.HasIndex(entity => entity.Code).IsUnique();
        builder.ToTable(table =>
        {
            table.HasCheckConstraint("ck_platform_approval_policies_version", "version > 0");
            table.HasCheckConstraint("ck_platform_approval_policies_expiry", "expires_after_hours between 1 and 720");
            table.HasCheckConstraint("ck_platform_approval_policies_threshold",
                "amount_threshold_cents is null or amount_threshold_cents > 0");
        });
    }
}

internal sealed class PlatformApprovalRequestConfiguration : IEntityTypeConfiguration<PlatformApprovalRequest>
{
    public void Configure(EntityTypeBuilder<PlatformApprovalRequest> builder)
    {
        builder.ConfigureEntity("platform_approval_requests");
        builder.ConfigureTimestamps();
        builder.Property(entity => entity.RequestNo).HasMaxLength(50);
        builder.Property(entity => entity.PolicyCode).HasMaxLength(120);
        builder.Property(entity => entity.Status).HasSnakeCaseEnum();
        builder.Property(entity => entity.RequiredPermission).HasMaxLength(200);
        builder.Property(entity => entity.CommandType).HasMaxLength(200);
        builder.Property(entity => entity.TargetType).HasMaxLength(100);
        builder.Property(entity => entity.TargetId).HasMaxLength(200);
        builder.Property(entity => entity.IdempotencyKey).HasMaxLength(200);
        builder.Property(entity => entity.RequestHash).HasMaxLength(64);
        builder.Property(entity => entity.RequestSnapshot).IsJson("{}");
        builder.Property(entity => entity.ResultSnapshot).HasColumnType("jsonb");
        builder.Property(entity => entity.RequestReason).HasMaxLength(1000);
        builder.Property(entity => entity.DecisionReason).HasMaxLength(1000);
        builder.Property(entity => entity.Error).HasMaxLength(4000);
        builder.Property(entity => entity.ConcurrencyStamp).IsConcurrencyToken();
        builder.HasIndex(entity => entity.RequestNo).IsUnique();
        builder.HasIndex(entity => new { entity.RequestedBy, entity.CommandType, entity.IdempotencyKey }).IsUnique();
        builder.HasIndex(entity => new { entity.Status, entity.ExpiresAt, entity.CreatedAt });
        builder.HasOne<User>().WithMany().HasForeignKey(entity => entity.RequestedBy).OnDelete(DeleteBehavior.Restrict);
        builder.HasOne<User>().WithMany().HasForeignKey(entity => entity.DecidedBy).OnDelete(DeleteBehavior.Restrict);
    }
}

internal sealed class
    PlatformConfigurationDefinitionConfiguration : IEntityTypeConfiguration<PlatformConfigurationDefinition>
{
    public void Configure(EntityTypeBuilder<PlatformConfigurationDefinition> builder)
    {
        builder.ConfigureEntity("platform_configuration_definitions");
        builder.ConfigureTimestamps();
        builder.Property(entity => entity.Code).HasMaxLength(120);
        builder.Property(entity => entity.Name).HasMaxLength(200);
        builder.Property(entity => entity.Category).HasMaxLength(100);
        builder.Property(entity => entity.ValueType).HasSnakeCaseEnum();
        builder.Property(entity => entity.Description).HasMaxLength(1000);
        builder.Property(entity => entity.ValidationSchema).IsJson("{}");
        builder.HasIndex(entity => entity.Code).IsUnique();
        builder.HasIndex(entity => new { entity.Category, entity.Code });
    }
}

internal sealed class PlatformConfigurationVersionConfiguration : IEntityTypeConfiguration<PlatformConfigurationVersion>
{
    public void Configure(EntityTypeBuilder<PlatformConfigurationVersion> builder)
    {
        builder.ConfigureEntity("platform_configuration_versions");
        builder.ConfigureTimestamps();
        builder.Property(entity => entity.Environment).HasMaxLength(80);
        builder.Property(entity => entity.Status).HasSnakeCaseEnum();
        builder.Property(entity => entity.Value).IsJson("{}");
        builder.Property(entity => entity.SecretRef).HasMaxLength(300);
        builder.Property(entity => entity.Reason).HasMaxLength(1000);
        builder.HasIndex(entity => new { entity.DefinitionId, entity.Environment, entity.Version }).IsUnique();
        builder.HasIndex(entity => new { entity.DefinitionId, entity.Environment, entity.Status });
        builder.HasOne<PlatformConfigurationDefinition>().WithMany().HasForeignKey(entity => entity.DefinitionId)
            .OnDelete(DeleteBehavior.Restrict);
        builder.HasOne<User>().WithMany().HasForeignKey(entity => entity.CreatedBy).OnDelete(DeleteBehavior.Restrict);
        builder.HasOne<User>().WithMany().HasForeignKey(entity => entity.PublishedBy).OnDelete(DeleteBehavior.Restrict);
        builder.HasOne<PlatformConfigurationVersion>().WithMany()
            .HasForeignKey(entity => entity.RolledBackFromVersionId).OnDelete(DeleteBehavior.Restrict);
    }
}

internal sealed class PlatformNotificationTemplateConfiguration : IEntityTypeConfiguration<PlatformNotificationTemplate>
{
    public void Configure(EntityTypeBuilder<PlatformNotificationTemplate> builder)
    {
        builder.ConfigureEntity("platform_notification_templates");
        builder.ConfigureTimestamps();
        builder.Property(entity => entity.Code).HasMaxLength(120);
        builder.Property(entity => entity.Name).HasMaxLength(200);
        builder.Property(entity => entity.Channel).HasSnakeCaseEnum();
        builder.Property(entity => entity.SubjectTemplate).HasMaxLength(500);
        builder.Property(entity => entity.BodyTemplate).HasMaxLength(8000);
        builder.Property(entity => entity.Variables).IsJson("[]");
        builder.HasIndex(entity => entity.Code).IsUnique();
    }
}

internal sealed class PlatformNotificationDeliveryConfiguration : IEntityTypeConfiguration<PlatformNotificationDelivery>
{
    public void Configure(EntityTypeBuilder<PlatformNotificationDelivery> builder)
    {
        builder.ConfigureEntity("platform_notification_deliveries");
        builder.ConfigureTimestamps();
        builder.Property(entity => entity.RecipientRoleCode).HasMaxLength(120);
        builder.Property(entity => entity.Channel).HasSnakeCaseEnum();
        builder.Property(entity => entity.Status).HasSnakeCaseEnum();
        builder.Property(entity => entity.Subject).HasMaxLength(500);
        builder.Property(entity => entity.Body).HasMaxLength(8000);
        builder.Property(entity => entity.IdempotencyKey).HasMaxLength(200);
        builder.Property(entity => entity.LastError).HasMaxLength(4000);
        builder.Property(entity => entity.Metadata).IsJson("{}");
        builder.HasIndex(entity => new { entity.TemplateId, entity.RecipientUserId, entity.IdempotencyKey }).IsUnique();
        builder.HasIndex(entity => new { entity.Status, entity.CreatedAt });
        builder.HasOne<PlatformNotificationTemplate>().WithMany().HasForeignKey(entity => entity.TemplateId)
            .OnDelete(DeleteBehavior.Restrict);
        builder.HasOne<User>().WithMany().HasForeignKey(entity => entity.RecipientUserId)
            .OnDelete(DeleteBehavior.Restrict);
        builder.HasOne<User>().WithMany().HasForeignKey(entity => entity.CreatedBy).OnDelete(DeleteBehavior.Restrict);
    }
}