from cpm_assessment import db
from datetime import date
from dateutil.relativedelta import relativedelta

class Client(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    date_of_birth = db.Column(db.Date, nullable=True) # Made nullable
    email = db.Column(db.String(120), nullable=True)
    phone_number = db.Column(db.String(20), nullable=True) # Made nullable
    gender = db.Column(db.String(10), nullable=True) # Made nullable
    referred_by_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=True) # Made nullable for admin creation
    referred_by = db.relationship('User', back_populates='clients') # Use back_populates
    is_active = db.Column(db.Boolean, nullable=False, default=True) # New field for client status
    skip_details_collection = db.Column(db.Boolean, nullable=False, default=False) # New field
    center_case_id = db.Column(db.String(64), unique=True, nullable=True)

    @property
    def age(self):
        """Calculates the current age of the client in years, months, and days."""
        if not self.date_of_birth:
            return "N/A"
        today = date.today()
        delta = relativedelta(today, self.date_of_birth)
        return f"{delta.years}Y, {delta.months}M, {delta.days}D"

    @property
    def age_in_months(self):
        """Calculates the precise age of the client in months."""
        if not self.date_of_birth:
            return 0
        today = date.today()
        months = (today.year - self.date_of_birth.year) * 12 + (today.month - self.date_of_birth.month)
        if today.day < self.date_of_birth.day:
            months -= 1
        return months

    def __repr__(self):
        return f"Client('{self.name}', '{self.email}', 'Active: {self.is_active}', 'Skip Details: {self.skip_details_collection}')"
