"""Phase B — Add Addon/AddonEntitlement + addon FK.

Migration steps 0005-0007 from the taxonomy refactor plan:
  0005: Create Addon, AddonEntitlement tables
  0006: [SKIPPED — table renames deferred to Phase D when Tier is dropped]
  0007: Add addon FK to TenantAddonFeature

Plan / PlanEntitlement aliases exist in code pointing to PlatformPlan / PlanFeature.
"""

import django.db.models.deletion
import uuid

from django.db import migrations, models


def _seed_default_addons(apps, schema_editor):
    """Insert canonical Addon rows."""
    Addon = apps.get_model("subscription", "Addon")
    defaults = [
        ("ai-assistant", "AI Assistant", "AI-powered assistant for all modules.", 500000, 5000000, 10),
        ("advanced-reporting", "Advanced Reporting", "Custom reports and analytics dashboards.", 300000, 3000000, 20),
        ("api-access", "API Access Pack", "Increased API rate limits and webhook volume.", 200000, 2000000, 30),
    ]
    for code, name, description, price_monthly, price_yearly, sort_order in defaults:
        Addon.objects.get_or_create(
            code=code,
            defaults={
                "name": name,
                "description": description,
                "price_monthly": price_monthly,
                "price_yearly": price_yearly,
                "sort_order": sort_order,
                "is_active": True,
            },
        )


class Migration(migrations.Migration):
    dependencies = [
        ("subscription", "0002_nullable_org_node"),
    ]

    operations = [
        # ── 0005: Addon model ─────────────────────────────────────────────
        migrations.CreateModel(
            name="Addon",
            fields=[
                (
                    "id",
                    models.BigAutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                    ),
                ),
                (
                    "public_id",
                    models.UUIDField(
                        db_index=True,
                        default=uuid.uuid4,
                        editable=False,
                        unique=True,
                        verbose_name="public id",
                    ),
                ),
                ("created_at", models.DateTimeField(auto_now_add=True, verbose_name="created at")),
                ("updated_at", models.DateTimeField(auto_now=True, verbose_name="updated at")),
                (
                    "code",
                    models.SlugField(
                        db_index=True,
                        help_text="Stable machine-readable code, e.g. 'ai-assistant'.",
                        max_length=40,
                        unique=True,
                        verbose_name="code",
                    ),
                ),
                ("name", models.CharField(max_length=200, verbose_name="name")),
                (
                    "description",
                    models.TextField(blank=True, default="", verbose_name="description"),
                ),
                (
                    "price_monthly",
                    models.DecimalField(
                        decimal_places=2, default=0, max_digits=12, verbose_name="monthly price",
                    ),
                ),
                (
                    "price_yearly",
                    models.DecimalField(
                        decimal_places=2, default=0, max_digits=12, verbose_name="yearly price",
                    ),
                ),
                ("is_active", models.BooleanField(default=True, verbose_name="active")),
                (
                    "sort_order",
                    models.PositiveSmallIntegerField(
                        db_index=True, default=0, verbose_name="sort order",
                    ),
                ),
            ],
            options={
                "verbose_name": "addon",
                "verbose_name_plural": "addons",
                "ordering": ("sort_order", "code"),
            },
        ),
        # ── 0005: AddonEntitlement model ──────────────────────────────────
        migrations.CreateModel(
            name="AddonEntitlement",
            fields=[
                (
                    "id",
                    models.BigAutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                    ),
                ),
                (
                    "public_id",
                    models.UUIDField(
                        db_index=True,
                        default=uuid.uuid4,
                        editable=False,
                        unique=True,
                        verbose_name="public id",
                    ),
                ),
                ("created_at", models.DateTimeField(auto_now_add=True, verbose_name="created at")),
                ("updated_at", models.DateTimeField(auto_now=True, verbose_name="updated at")),
                (
                    "feature_key",
                    models.CharField(
                        db_index=True,
                        help_text="Dotted key, e.g. 'ai.assistant'.",
                        max_length=120,
                        verbose_name="feature key",
                    ),
                ),
                (
                    "enabled_by_default",
                    models.BooleanField(default=True, verbose_name="enabled by default"),
                ),
                (
                    "config_json",
                    models.JSONField(
                        blank=True,
                        default=dict,
                        help_text="Limits, e.g. {'max': 100}",
                        verbose_name="config",
                    ),
                ),
                (
                    "addon",
                    models.ForeignKey(
                        on_delete=django.db.models.deletion.CASCADE,
                        related_name="entitlements",
                        to="subscription.Addon",
                        verbose_name="addon",
                    ),
                ),
            ],
            options={
                "verbose_name": "addon entitlement",
                "verbose_name_plural": "addon entitlements",
                "ordering": ("addon__code", "feature_key"),
            },
        ),
        # Add unique constraint on AddonEntitlement
        migrations.AddConstraint(
            model_name="addonentitlement",
            constraint=models.UniqueConstraint(
                fields=("addon", "feature_key"),
                name="subscription_addonentitlement_unique",
            ),
        ),
        # ── 0007: Add addon FK to TenantAddonFeature ──────────────────────
        migrations.AddField(
            model_name="tenantaddonfeature",
            name="addon",
            field=models.ForeignKey(
                blank=True,
                help_text="The addon product this purchase is for.",
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="tenant_purchases",
                to="subscription.Addon",
                verbose_name="addon",
            ),
        ),
        # ── Seed data ─────────────────────────────────────────────────────
        migrations.RunPython(_seed_default_addons, migrations.RunPython.noop),
    ]
