from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
from datetime import datetime
from app import db

class User(db.Model, UserMixin):
    __tablename__ = 'users'
    __table_args__ = {'extend_existing': True}

    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password_hash = db.Column(db.Text, nullable=False)
    role = db.Column(db.String(50), default='user')
    is_verified = db.Column(db.Boolean, default=False)
    excluded_from_analytics = db.Column(db.Boolean, default=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    # Use back_populates, not backref
    submitted_submissions = db.relationship(
        "Submission",
        foreign_keys="Submission.user_id",
        back_populates="submitter",
        lazy=True
    )

    reviewed_submissions = db.relationship(
        "Submission",
        foreign_keys="Submission.reviewed_by",
        back_populates="reviewer",
        lazy=True
    )

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)
