import mysql.connector
from flask import Blueprint, flash, redirect, render_template, request, session
from werkzeug.security import check_password_hash
from config.db_config import DatabaseConfig

auth = Blueprint("auth", __name__, template_folder="templates")


def get_db():
    return mysql.connector.connect(
        host=DatabaseConfig.DB_HOST,
        port=DatabaseConfig.DB_PORT,
        user=DatabaseConfig.DB_USER,
        password=DatabaseConfig.DB_PASSWORD,
        database=DatabaseConfig.DB_NAME
    )


@auth.route('/login', methods=['GET', 'POST'])
def login():
    # Already logged in → redirect by role
    if session.get("user_id"):
        role = session.get("role", "photographer")
        if role == 'admin':
            return redirect('/admin/dashboard')
        elif role == 'sub_admin':
            return redirect('/subadmin/dashboard')
        return redirect('/upload')

    if request.method == 'POST':
        username = request.form.get('username', '').strip()
        password = request.form.get('password', '').strip()

        # Validate credentials
        conn   = get_db()
        cursor = conn.cursor(dictionary=True)
        cursor.execute(
            "SELECT * FROM users_auth WHERE username = %s LIMIT 1",
            (username,)
        )
        user = cursor.fetchone()
        cursor.close()
        conn.close()

        is_valid = False
        if user:
            if user['password'] == password:
                is_valid = True
            else:
                try:
                    is_valid = check_password_hash(user['password'], password)
                except Exception:
                    pass

        if not is_valid:
            flash("Invalid username or password.", "error")
            return render_template('login.html')

        # Login success
        role = user.get('role', 'photographer')
        session.clear()
        session['user_id']         = user['id']
        session['role']            = role
        session['username']        = user['username']
        session['admin_logged_in'] = True
        session['admin_username']  = user['username']
        session['admin_role']      = role
        session.permanent          = True

        if role == 'admin':
            return redirect('/admin/dashboard')
        elif role == 'sub_admin':
            return redirect('/subadmin/dashboard')
        return redirect('/upload')

    return render_template('login.html')


@auth.route('/logout', methods=['GET', 'POST'])
def logout():
    session.clear()
    flash("Logged out successfully", "success")
    return redirect('/login')