"""Invoice retrieval operations."""

from __future__ import annotations

from datetime import UTC, datetime

import stripe

from billing.models import Invoice
from billing.subscriptions import _get_customer_id


def get_invoices(user_id: str, limit: int = 10) -> list[Invoice]:
    """Fetch recent invoices for a user.

    Args:
        user_id: Internal user identifier.
        limit: Maximum number of invoices to return. Defaults to 10.

    Returns:
        List of Invoice objects, most recent first.

    Raises:
        ValueError: If no Stripe customer is found for the user.
        stripe.StripeError: On Stripe API failures.
    """
    customer_id = _get_customer_id(user_id)

    stripe_invoices = stripe.Invoice.list(
        customer=customer_id,
        limit=limit,
    )

    invoices: list[Invoice] = []
    for inv in stripe_invoices.data:
        invoices.append(
            Invoice(
                id=inv.id,
                amount=inv.amount_paid or inv.amount_due,
                currency=inv.currency,
                status=inv.status,
                created=datetime.fromtimestamp(inv.created, tz=UTC),
                pdf_url=inv.invoice_pdf,
            )
        )

    return invoices
