import json
import os
import random
from datetime import datetime, timedelta
from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks, status
from fastapi.responses import JSONResponse
from app.db import database
from app.v1.models.saas.usersmodel import User, UserLogin, UserResponse, GoogleToken
from app.v1.dependencies.auth import get_current_userdetails
from app.v1.services.saas.login import login_user, google_connect_user, process_user_login, verify_phone_otp_service
from dotenv import load_dotenv

load_dotenv()
router = APIRouter()
ACCESS_TOKEN_EXPIRES = timedelta(minutes=14320)

# In-memory OTP store (for demonstration only)
otp_store = {}

@router.post("/", response_model=User, tags=["Auth"])
async def login(user: UserLogin, db: database.MongoDB = Depends(database.get_mongo_db)):
    result = await login_user(user, db)
    response = JSONResponse(content={"message": result["message"], "user": result["user"]})
    response.set_cookie(
        key="Authorization",
        value=f"Bearer {result['token']}",
        httponly=True,
        max_age=180000,
        expires=180000,
        path="/",
        secure=True,
        samesite="None"
    )
    return response

@router.post("/google", response_model=UserResponse, tags=["Auth"])
async def google_connect(google_token: GoogleToken, background_tasks: BackgroundTasks, db: database.MongoDB = Depends(database.get_mongo_db)):
    result = await google_connect_user(google_token, background_tasks, db)
    response = JSONResponse(content={"message": result["message"], "user": result["user"]})
    response.set_cookie(
        key="Authorization",
        value=f"Bearer {result['token']}",
        httponly=True,
        max_age=180000,
        expires=180000,
        path="/",
        secure=True,
        samesite="None"
    )
    return response

@router.post("/phone/send-otp", tags=["Auth"])
async def send_phone_otp(payload: dict):
    phone = payload.get("phone")
    if not phone:
        raise HTTPException(status_code=400, detail="Phone number is required.")
    
    otp = random.randint(100000, 999999)
    otp_store[phone] = {"otp": otp, "expires": datetime.utcnow() + timedelta(minutes=5)}
    
    # Replace the print statement with an actual SMS service call.
    print(f"Sending OTP {otp} to phone {phone}")
    return {"message": "OTP sent successfully."}

@router.post("/phone/verify", tags=["Auth"])
async def verify_phone_otp(payload: dict, db: database.MongoDB = Depends(database.get_mongo_db)):
    # Delegate phone OTP verification to the service layer.
    result = await verify_phone_otp_service(payload, db, otp_store)
    # For mobile clients, simply return the result without setting cookies.
    return result

@router.get("/check", tags=["Auth"])
async def auth_check(db: database.MongoDB = Depends(database.get_mongo_db),
                     current_user: User = Depends(get_current_userdetails)):
    if current_user:
        return {"authenticated": True}
    raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Unauthorized")
