"""DictIA subscription model — Stripe subscription state mirror (B-2.8).

This table is updated EXCLUSIVELY by the Stripe webhook handler. Never
write to it from user-facing routes (Checkout creates the Stripe
subscription; webhook reflects its state into our DB).

Each row corresponds to one Stripe Subscription object. A user can have
multiple historical subscriptions (renewed, cancelled, re-subscribed).
"""
from datetime import datetime
from src.database import db


class Subscription(db.Model):
    """One row per Stripe Subscription. The active row for a user is the
    one with status in ('active', 'trialing', 'past_due') ordered by
    created_at DESC."""
    __tablename__ = 'subscription'

    id = db.Column(db.Integer, primary_key=True)
    # Use ondelete=SET NULL so we keep historical billing records even if
    # the user deletes their account (Loi 25 art. 28.1 right-to-erasure +
    # accounting/tax retention obligations are reconciled by anonymizing
    # rather than dropping the row).
    user_id = db.Column(
        db.Integer,
        db.ForeignKey('user.id', ondelete='SET NULL'),
        nullable=True,
        index=True,
    )

    stripe_customer_id = db.Column(db.String(120), nullable=False, index=True)
    # Stripe subscription ID is unique — UNIQUE constraint also gives natural
    # dedup against duplicate webhook deliveries of checkout.session.completed
    stripe_subscription_id = db.Column(db.String(120), unique=True, nullable=False)
    plan_slug = db.Column(db.String(40), nullable=False)
    period = db.Column(db.String(10), nullable=False)  # 'monthly' | 'yearly'

    # Stripe subscription status: 'trialing' | 'active' | 'past_due' |
    # 'canceled' | 'incomplete' | 'incomplete_expired' | 'unpaid' | 'paused'
    status = db.Column(db.String(20), nullable=False, index=True)

    # Period end: when next invoice will be billed (or when access expires
    # if status='canceled' with cancel_at_period_end=True)
    current_period_end = db.Column(db.DateTime, nullable=True)

    # When the subscription was first created in Stripe
    created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
    # Last time we received a webhook event updating this subscription
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)

    user = db.relationship('User', backref='subscriptions')

    def __repr__(self):
        return f'<Subscription {self.stripe_subscription_id} {self.status} {self.plan_slug}/{self.period}>'
