"""SaaS Organization and Tenant Subscription Models.

Represents an NGO tenant on the SaaS platform and their active subscription.
"""

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


class Organization(db.Model):
    """
    Multi-Tenant Organization (NGO / Non-Profit) entity.
    Isolates data, users, branding, and billing per NGO.
    """
    __tablename__ = 'organizations'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(150), nullable=False)
    slug = db.Column(db.String(80), unique=True, nullable=False, index=True)
    registration_number = db.Column(db.String(100), nullable=True)
    tagline = db.Column(db.String(255), nullable=True)
    description = db.Column(db.Text, nullable=True)
    
    # Custom Branding
    logo_url = db.Column(db.String(255), nullable=True)
    primary_color = db.Column(db.String(20), default='#102a43')
    secondary_color = db.Column(db.String(20), default='#0284c7')
    
    # Contact Info
    contact_email = db.Column(db.String(120), nullable=False)
    contact_phone = db.Column(db.String(30), nullable=True)
    address = db.Column(db.String(255), nullable=True)
    website_url = db.Column(db.String(255), nullable=True)
    
    # Status: 'trial', 'active', 'suspended', 'pending_approval'
    status = db.Column(db.String(30), default='active', nullable=False)
    
    # Associated SaaS Plan
    plan_id = db.Column(db.Integer, db.ForeignKey('subscription_plans.id'), nullable=True)
    plan = db.relationship('SubscriptionPlan', backref='organizations')
    
    trial_ends_at = db.Column(db.DateTime, nullable=True)
    created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc))

    # Relationships
    users = db.relationship('User', back_populates='organization', lazy='dynamic')
    subscriptions = db.relationship('TenantSubscription', backref='organization', lazy='dynamic', cascade='all, delete-orphan')

    @property
    def is_active(self):
        return self.status in ('active', 'trial')

    @property
    def is_trial(self):
        return self.status == 'trial'

    @property
    def is_expired(self):
        """Returns True if the trial/validity date has passed."""
        if not self.trial_ends_at:
            return False
        trial = self.trial_ends_at.replace(tzinfo=None) if self.trial_ends_at.tzinfo else self.trial_ends_at
        return trial < datetime.now()

    @property
    def days_remaining(self):
        """Returns number of days remaining until validity/trial expires."""
        if not self.trial_ends_at:
            return None
        trial = self.trial_ends_at.replace(tzinfo=None) if self.trial_ends_at.tzinfo else self.trial_ends_at
        diff = (trial.date() - datetime.now().date()).days
        return diff

    @property
    def current_subscription(self):
        return self.subscriptions.order_by(TenantSubscription.id.desc()).first()

    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'slug': self.slug,
            'registration_number': self.registration_number,
            'tagline': self.tagline,
            'logo_url': self.logo_url,
            'primary_color': self.primary_color,
            'secondary_color': self.secondary_color,
            'contact_email': self.contact_email,
            'contact_phone': self.contact_phone,
            'address': self.address,
            'status': self.status,
            'plan_name': self.plan.name if self.plan else 'None',
            'created_at': self.created_at.isoformat() if self.created_at else None,
        }


class TenantSubscription(db.Model):
    """
    Tracks subscription records, renewals, and invoice history for a tenant NGO.
    """
    __tablename__ = 'tenant_subscriptions'

    id = db.Column(db.Integer, primary_key=True)
    organization_id = db.Column(db.Integer, db.ForeignKey('organizations.id'), nullable=False, index=True)
    plan_id = db.Column(db.Integer, db.ForeignKey('subscription_plans.id'), nullable=False)
    plan = db.relationship('SubscriptionPlan')
    
    # Status: 'active', 'trial', 'past_due', 'cancelled'
    status = db.Column(db.String(30), default='active', nullable=False)
    billing_cycle = db.Column(db.String(20), default='monthly', nullable=False) # 'monthly' or 'yearly'
    amount_paid = db.Column(db.Float, default=0.0, nullable=False)
    payment_reference = db.Column(db.String(100), nullable=True)
    
    start_date = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc))
    end_date = db.Column(db.DateTime, nullable=True)
    auto_renew = db.Column(db.Boolean, default=True)
    
    created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc))
