from flask import Blueprint, render_template
from flask_login import login_required, current_user
from app.models import Job

dashboard_bp = Blueprint('dashboard', __name__, url_prefix='/dashboard')

@dashboard_bp.route('/')
@login_required
def index():
    username_query = request.args.get('username')
    job_id_query = request.args.get('job_id')
    
    query = Job.query
    
    # Global search by Job ID
    if job_id_query:
        query = query.filter(Job.id == job_id_query)
    # Global search by Username
    elif username_query:
        from app.models import User
        query = query.join(User).filter(User.username.ilike(f'%{username_query}%'))
    # Default view
    else:
        if not current_user.is_admin:
            query = query.filter(Job.user_id == current_user.id)
            
    jobs = query.order_by(Job.submitted_at.desc()).all()
    
    return render_template('dashboard/index.html', 
                         jobs=jobs, 
                         username_query=username_query, 
                         job_id_query=job_id_query)
