from cpm_assessment import db
from sqlalchemy.schema import CheckConstraint

class Response(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 responses
    assessment_id = db.Column(db.Integer, db.ForeignKey('assessment.id'), nullable=False)
    assessment_assignment_id = db.Column(db.Integer, db.ForeignKey('assessment_assignment.id'), nullable=False)
    question_id = db.Column(db.Integer, db.ForeignKey('question.id'), nullable=False)
    choice_id = db.Column(db.Integer, db.ForeignKey('choice.id'), nullable=False)

    client = db.relationship('Client', backref='responses')
    user = db.relationship('User', backref='responses') # New relationship
    assessment = db.relationship('Assessment', backref='responses')
    assignment = db.relationship('AssessmentAssignment', backref=db.backref('responses', cascade='all, delete-orphan'))
    question = db.relationship('Question', backref='responses')
    choice = db.relationship('Choice', backref='responses')

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

    def __repr__(self):
        return f"Response(Client: {self.client_id}, User: {self.user_id}, Assignment: {self.assessment_assignment_id}, Question: {self.question_id}, Choice: {self.choice_id})"
