# Generated by Django 4.2.10 on 2024-03-01 14:05

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


def fix_plans_on_free_trial_with_changes_in_schedule(
    apps: StateApps, schema_editor: BaseDatabaseSchemaEditor
) -> None:
    CustomerPlan = apps.get_model("corporate", "CustomerPlan")
    LicenseLedger = apps.get_model("corporate", "LicenseLedger")
    CustomerPlan.FREE_TRIAL = 3
    CustomerPlan.ENDED = 11
    CustomerPlan.INVOICING_STATUS_DONE = 1

    plans_on_free_trial_with_changed_schedule = CustomerPlan.objects.filter(
        status=CustomerPlan.FREE_TRIAL, invoiced_through=None
    )
    for plan in plans_on_free_trial_with_changed_schedule:
        assert plan.customer is not None
        assert plan.billing_cycle_anchor is not None

        ledger_entries = LicenseLedger.objects.filter(
            plan=plan,
            is_renewal=True,
            event_time=plan.billing_cycle_anchor,
        )
        assert ledger_entries.count() == 1
        plan.invoiced_through = ledger_entries.first()
        plan.invoicing_status = CustomerPlan.INVOICING_STATUS_DONE
        plan.save(update_fields=["invoiced_through", "invoicing_status"])

        CustomerPlan.objects.filter(
            customer=plan.customer,
            status=CustomerPlan.ENDED,
            billing_cycle_anchor=plan.billing_cycle_anchor,
        ).update(next_invoice_date=None)


class Migration(migrations.Migration):
    dependencies = [
        ("corporate", "0040_customerplan_reminder_to_review_plan_email_sent"),
    ]

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