# Generated by Django 4.2.8 on 2024-01-24 08:08

from django.db import migrations
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.migrations.state import StateApps


def fix_customer_plans_scheduled_after_legacy_plan(
    apps: StateApps, schema_editor: BaseDatabaseSchemaEditor
) -> None:
    CustomerPlan = apps.get_model("corporate", "CustomerPlan")
    CustomerPlan.TIER_SELF_HOSTED_LEGACY = 101
    CustomerPlan.SWITCH_PLAN_TIER_AT_PLAN_END = 8
    CustomerPlan.NEVER_STARTED = 12
    CustomerPlan.INVOICING_STATUS_INITIAL_INVOICE_TO_BE_SENT = 3

    # Legacy plans scheduled to switch to a new plan.
    legacy_plans = CustomerPlan.objects.filter(
        tier=CustomerPlan.TIER_SELF_HOSTED_LEGACY, status=CustomerPlan.SWITCH_PLAN_TIER_AT_PLAN_END
    )

    for legacy_plan in legacy_plans:
        CustomerPlan.objects.filter(
            customer=legacy_plan.customer,
            billing_cycle_anchor=legacy_plan.end_date,
            status=CustomerPlan.NEVER_STARTED,
        ).update(
            next_invoice_date=legacy_plan.end_date,
            invoicing_status=CustomerPlan.INVOICING_STATUS_INITIAL_INVOICE_TO_BE_SENT,
        )


class Migration(migrations.Migration):
    dependencies = [
        ("corporate", "0035_update_legacy_plan_next_invoice_date"),
    ]

    operations = [
        migrations.RunPython(fix_customer_plans_scheduled_after_legacy_plan, elidable=True),
    ]
