from cpm_assessment import db
import uuid
from sqlalchemy.schema import CheckConstraint

class AssessmentAssignment(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    client_id = db.Column(db.Integer, db.ForeignKey('client.id'), nullable=True) # Made nullable
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=True) # New field for direct user assignments
    assessment_id = db.Column(db.Integer, db.ForeignKey('assessment.id'), nullable=False)
    invitation_id = db.Column(db.Integer, db.ForeignKey('assessment_invitation.id'), nullable=True) # New field to link to invitation
    unique_token = db.Column(db.String(36), unique=True, nullable=False, default=lambda: str(uuid.uuid4()))
    assigned_date = db.Column(db.DateTime, nullable=False, default=db.func.current_timestamp())
    completed_date = db.Column(db.DateTime, nullable=True)
    is_completed = db.Column(db.Boolean, nullable=False, default=False)
    therapist_notes = db.Column(db.Text, nullable=True) # Field for therapist notes

    client = db.relationship('Client', backref='assessment_assignments')
    user = db.relationship('User', backref=db.backref('direct_assessment_assignments', cascade='all, delete-orphan')) # New relationship
    invitation = db.relationship('AssessmentInvitation', backref='assignments') # New relationship

    __table_args__ = (
        CheckConstraint('(client_id IS NOT NULL) OR (user_id IS NOT NULL)', name='chk_client_or_user'),
    )

    def __repr__(self):
        return f"AssessmentAssignment(Client: {self.client_id}, User: {self.user_id}, Assessment: {self.assessment_id}, Token: {self.unique_token})"
