from datetime import datetime
from itsdangerous import URLSafeTimedSerializer as Serializer
from flask import current_app
from cpm_assessment import db

class AssessmentInvitation(db.Model):
    """
    Represents an invitation for a specific person to take a specific assessment.
    This model is used to generate secure, one-time-use links.
    """
    id = db.Column(db.Integer, primary_key=True)
    recipient_email = db.Column(db.String(120), nullable=False, index=True)
    status = db.Column(db.String(20), nullable=False, default='pending')  # e.g., 'pending', 'completed'
    created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    completed_at = db.Column(db.DateTime, nullable=True)

    # Foreign Key to the Assessment model
    assessment_id = db.Column(db.Integer, db.ForeignKey('assessment.id'), nullable=False)

    def get_assessment_token(self, expires_sec=86400):
        """
        Generates a secure token for this invitation, valid for 24 hours by default.
        The token contains the invitation ID.
        """
        s = Serializer(current_app.config['SECRET_KEY'])
        return s.dumps({'invitation_id': self.id})

    @staticmethod
    def verify_assessment_token(token, expires_sec=86400):
        """
        Verifies the assessment token.

        Returns:
            AssessmentInvitation: The invitation object if the token is valid and not yet used, otherwise None.
        """
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            # The max_age parameter checks the token's age.
            invitation_id = s.loads(token, max_age=expires_sec)['invitation_id']
        except:
            # Catches expired or invalid tokens
            return None
        
        invitation = AssessmentInvitation.query.get(invitation_id)
        
        # Ensure the invitation is still pending (hasn't been used)
        if invitation and invitation.status == 'pending':
            return invitation
        
        return None

    def __repr__(self):
        return f"AssessmentInvitation(email='{self.recipient_email}', assessment_id={self.assessment_id}, status='{self.status}')"