"""
Auto-Pay and Recurring Subscription Models for NGO Foundation.
Provides digital recurring donor mandates, automated monthly contributions,
lifecycle management (Active, Paused, Cancelled), and audit tracking.
All code contains proper English comments for clarity and maintenance.
"""

from datetime import date, datetime, timezone
from app.extensions import db


class AutoPaySubscription(db.Model):
    """
    SQLAlchemy model representing an automated recurring donation mandate (Auto-Pay).
    Stores monthly deduction amount, scheduled billing day, gateway subscription tokens,
    fulfillment cycle counters, and live mandate lifecycle status.
    All code contains proper English comments for clarity and maintenance.
    """
    __tablename__ = 'autopay_subscriptions'

    # Primary key identifier
    id = db.Column(db.Integer, primary_key=True)

    # Unique sequential mandate reference code (e.g., MND-2026-0001)
    mandate_code = db.Column(db.String(50), unique=True, nullable=False, index=True)

    # Donor identification credentials
    donor_name = db.Column(db.String(120), nullable=False)
    donor_email = db.Column(db.String(120), nullable=False, index=True)
    donor_phone = db.Column(db.String(30), nullable=True)
    donor_pan = db.Column(db.String(20), nullable=True, index=True)
    donor_address = db.Column(db.String(255), nullable=True)

    # Financial and billing schedule parameters
    amount = db.Column(db.Float, nullable=False)
    currency = db.Column(db.String(10), default='INR', nullable=False)
    billing_day = db.Column(db.Integer, default=5, nullable=False)  # Day of month (1 to 28)
    purpose = db.Column(db.String(150), default='General Mission Support', nullable=False)

    # Mandate lifecycle status: 'active', 'paused', 'cancelled', 'completed'
    status = db.Column(db.String(30), default='active', nullable=False, index=True)

    # Payment Gateway Provider details ('mock_simulator', 'razorpay', 'phonepe', 'payu')
    gateway = db.Column(db.String(50), default='mock_simulator', nullable=False)
    gateway_subscription_id = db.Column(db.String(120), nullable=True, index=True)
    gateway_customer_id = db.Column(db.String(120), nullable=True)

    # Schedule milestones
    start_date = db.Column(db.Date, default=date.today, nullable=False)
    next_billing_date = db.Column(db.Date, nullable=False)
    last_billing_date = db.Column(db.Date, nullable=True)

    # Aggregate performance counters
    total_cycles_completed = db.Column(db.Integer, default=0, nullable=False)
    total_amount_collected = db.Column(db.Float, default=0.0, nullable=False)
    failed_cycles_count = db.Column(db.Integer, default=0, nullable=False)
    last_failure_reason = db.Column(db.String(255), nullable=True)

    # Optional cancellation audit records
    cancellation_reason = db.Column(db.Text, nullable=True)
    cancelled_at = db.Column(db.DateTime, nullable=True)

    # Optional link to registered User account
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True, index=True)
    user = db.relationship('User', foreign_keys=[user_id], backref=db.backref('autopay_mandates', lazy='dynamic'))

    # Member Referral Attribution (Module 9)
    referred_by_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True, index=True)
    referrer = db.relationship('User', foreign_keys=[referred_by_id], backref=db.backref('referred_mandates', lazy='dynamic'))

    # Relationship to all donation settlement records generated by this recurring mandate
    donations = db.relationship('Donation', backref='autopay_subscription', lazy='dynamic', order_by='Donation.donated_at.desc()')

    # Timestamps
    created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc), nullable=False)
    updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc), nullable=False)

    @property
    def is_active(self) -> bool:
        """Returns True if mandate is currently active and eligible for automated recurring billing."""
        return self.status == 'active'

    @property
    def formatted_amount(self) -> str:
        """Formats the monthly recurring donation amount in Indian Rupee format."""
        return f"₹{self.amount:,.2f}"

    @property
    def formatted_total_collected(self) -> str:
        """Formats cumulative donations collected under this mandate in Indian Rupee format."""
        return f"₹{self.total_amount_collected:,.2f}"

    @property
    def status_badge_class(self) -> str:
        """Returns appropriate Bootstrap badge color class based on mandate status."""
        mapping = {
            'active': 'bg-success text-white',
            'paused': 'bg-warning text-dark',
            'cancelled': 'bg-danger text-white',
            'completed': 'bg-primary text-white',
        }
        return mapping.get(self.status, 'bg-secondary text-white')

    def __repr__(self) -> str:
        """String representation of AutoPaySubscription."""
        return f"<AutoPaySubscription {self.mandate_code} - {self.donor_name} (₹{self.amount}/mo - {self.status})>"
