import jwt
from datetime import datetime, timedelta
from sqlalchemy import select
from app.database.connection import SessionLocal
from app.models.user import tbl_user

SECRET_KEY = "your_secret_key"
ALGORITHM = "HS256"

def create_jwt_token(username: str) -> str:
    payload = {
        "sub": username,
        "exp": datetime.utcnow() + timedelta(hours=2)
    }
    return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)

def verify_user(username: str, password: str) -> bool:
    print("🔧 verify_user() called")
    print(f"👤 Username received: {username}")
    print(f"🔓 Password received: {password}")

    db = SessionLocal()
    try:
        print("🔎 Querying database for user...")
        stmt = select(tbl_user.c.username, tbl_user.c.password_hash).where(tbl_user.c.username == username)
        result = db.execute(stmt).fetchone()

        if result is None:
            print("❌ User not found in database!")
            return False

        db_username, db_password = result
        print(f"✅ User found in DB: {db_username}")
        print(f"📦 Password in DB: {db_password}")
        print(f"🔑 Password from input: {password}")

        if db_password == password:
            print("✅ Plain text password matched. Login successful.")
            return True
        else:
            print("❌ Plain text password mismatch!")
            return False
    except Exception as e:
        print("❗ Exception during DB check:", str(e))
        return False
    finally:
        db.close()
        print("🔁 Database session closed.")
