"""
Invoice generation service.

Creates immutable Invoice records with snapshot data from the subscription.
"""

from __future__ import annotations

from datetime import datetime
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from smoothschedule.billing.models import Subscription

from smoothschedule.billing.models import Invoice
from smoothschedule.billing.models import InvoiceLine


def generate_invoice_for_subscription(
    subscription: Subscription,
    period_start: datetime,
    period_end: datetime,
) -> Invoice:
    """
    Creates an Invoice + InvoiceLines with SNAPSHOT values.

    1. Creates Invoice with plan snapshots
    2. Creates line item for base plan
    3. Creates line items for active add-ons
    4. Calculates subtotal, tax, total
    5. Returns created Invoice

    Note: Prices are snapshotted - future plan price changes
    do NOT affect existing invoices.

    Args:
        subscription: The Subscription to invoice
        period_start: Start of the billing period
        period_end: End of the billing period

    Returns:
        The created Invoice instance
    """
    plan_version = subscription.plan_version

    # Create invoice with snapshot data
    invoice = Invoice(
        business=subscription.business,
        subscription=subscription,
        period_start=period_start,
        period_end=period_end,
        # Snapshot values - these are IMMUTABLE
        plan_code_at_billing=plan_version.plan.code,
        plan_name_at_billing=plan_version.name,
        plan_version_id_at_billing=plan_version.id,
    )
    invoice.save()

    # Track totals
    subtotal = 0

    # Create line item for base plan
    plan_amount = plan_version.price_monthly_cents
    plan_line = InvoiceLine(
        invoice=invoice,
        line_type="plan",
        description=f"{plan_version.name} - Monthly Subscription",
        quantity=1,
        unit_amount=plan_amount,
        subtotal_amount=plan_amount,
        tax_amount=0,  # Tax calculation is stubbed
        total_amount=plan_amount,
        plan_version=plan_version,
    )
    plan_line.save()
    subtotal += plan_amount

    # Create line items for active add-ons
    active_addons = subscription.addons.filter(status="active").all()
    for subscription_addon in active_addons:
        if not subscription_addon.is_active:
            continue

        addon = subscription_addon.addon
        addon_amount = addon.price_monthly_cents

        addon_line = InvoiceLine(
            invoice=invoice,
            line_type="addon",
            description=f"{addon.name} - Add-On",
            quantity=1,
            unit_amount=addon_amount,
            subtotal_amount=addon_amount,
            tax_amount=0,  # Tax calculation is stubbed
            total_amount=addon_amount,
            addon=addon,
        )
        addon_line.save()
        subtotal += addon_amount

    # Update invoice totals
    invoice.subtotal_amount = subtotal
    invoice.discount_amount = 0  # Discount calculation is stubbed
    invoice.tax_amount = 0  # Tax calculation is stubbed
    invoice.total_amount = subtotal  # subtotal - discount + tax
    invoice.save()

    return invoice
