from cpm_assessment import db
from flask_login import UserMixin
from datetime import date

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password = db.Column(db.String(60), nullable=False)
    role = db.Column(db.String(20), nullable=False, default='user')
    is_active = db.Column(db.Boolean, nullable=False, default=True) # New field for suspension
    mobile_number = db.Column(db.String(20), unique=True, nullable=True)
    date_of_birth = db.Column(db.Date, nullable=True)
    gender = db.Column(db.String(10), nullable=True)
    
    # Consultant profile fields
    registration_number = db.Column(db.String(100), nullable=True)
    contact_details = db.Column(db.Text, nullable=True)
    logo_filename = db.Column(db.String(100), nullable=True)
    
    # User-consultant assignment
    assigned_consultant_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=True)
    
    clients = db.relationship('Client', back_populates='referred_by', lazy=True) # Use back_populates
    assessment_requests = db.relationship('AssessmentRequest', back_populates='consultant', lazy=True) # Use back_populates
    
    # Relationships for user-consultant assignment
    assigned_consultant = db.relationship('User', remote_side=[id], backref='assigned_users')

    @property
    def name(self):
        return self.username

    @property
    def age(self):
        if self.date_of_birth:
            today = date.today()
            return today.year - self.date_of_birth.year - ((today.month, today.day) < (self.date_of_birth.month, self.date_of_birth.day))
        return None

    def __repr__(self):
        return f"User('{self.username}', '{self.email}', '{self.role}', 'Active: {self.is_active}')"
