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

class User(UserMixin, db.Model):
    __tablename__ = 'users'
    
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    password_hash = db.Column(db.String(255), nullable=False)
    is_admin = db.Column(db.Boolean, default=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    jobs = db.relationship('Job', backref='submitter', lazy=True, cascade='all, delete-orphan')
    
    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)

class Job(db.Model):
    __tablename__ = 'jobs'
    
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    branch_name = db.Column(db.String(255), nullable=False)
    scenarios = db.Column(db.Text, nullable=False)  # JSON string
    environment = db.Column(db.String(50), nullable=False)
    test_mode = db.Column(db.String(50), nullable=False)
    status = db.Column(db.String(20), default='in_progress')  # in_progress, passed, failed, aborted
    submitted_at = db.Column(db.DateTime, default=datetime.utcnow)
    completed_at = db.Column(db.DateTime, nullable=True)
    duration = db.Column(db.Integer, nullable=True)  # in seconds
    keep_devbenches = db.Column(db.Boolean, default=False)
    reuse_results = db.Column(db.Boolean, default=False)
    results_path = db.Column(db.String(500), nullable=True)
    
    def get_status_icon(self):
        icons = {
            'in_progress': '🟠',
            'passed': '🟢',
            'failed': '🔴',
            'aborted': '⚫'
        }
        return icons.get(self.status, '⚪')
