from fastapi import APIRouter, HTTPException, Depends
from models.schemas import AdminLogin
from auth import hash_password, verify_password, create_access_token
from motor.motor_asyncio import AsyncIOMotorClient
import os

router = APIRouter(prefix="/api/auth", tags=["Authentication"])

# MongoDB connection will be injected
db = None

def set_db(database):
    global db
    db = database

@router.post("/login")
async def login(credentials: AdminLogin):
    """Admin login endpoint"""
    # Find admin user
    admin = await db.admin_users.find_one({"email": credentials.email})
    
    if not admin:
        raise HTTPException(status_code=401, detail="Invalid email or password")
    
    # Verify password
    if not verify_password(credentials.password, admin["password_hash"]):
        raise HTTPException(status_code=401, detail="Invalid email or password")
    
    # Create access token
    access_token = create_access_token(data={"sub": admin["email"]})
    
    return {
        "access_token": access_token,
        "token_type": "bearer",
        "email": admin["email"]
    }

@router.post("/verify")
async def verify_token(admin: dict = Depends(lambda: __import__('auth').get_current_admin)):
    """Verify JWT token"""
    return {"valid": True, "email": admin["email"]}

@router.post("/initialize-admin")
async def initialize_admin():
    """Initialize default admin user (for development/setup only)"""
    # Check if admin already exists
    existing_admin = await db.admin_users.find_one({"email": "admin@epictravel.com"})
    
    if existing_admin:
        return {"message": "Admin user already exists"}
    
    # Create default admin
    admin_data = {
        "email": "admin@epictravel.com",
        "password_hash": hash_password("admin123"),
        "created_at": __import__('datetime').datetime.utcnow()
    }
    
    await db.admin_users.insert_one(admin_data)
    
    return {"message": "Admin user created successfully", "email": "admin@epictravel.com"}
