from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks, Path, Request
from fastapi.responses import JSONResponse
from typing import List, Optional
import json

from app.db import database
from ...models.saas.usersmodel import (
    User, UserBase, UserLogin, UserUpdate, 
    UserResponseList, EmailAction, ResetPasswordRequest
)
from ...dependencies.auth import create_access_token, get_current_userdetails
from ...libraries.object import str_to_objectid

# Import service functions
from ...services.saas.users import (
    create_user_service,
    send_email_verification_service,
    get_users_service,
    read_user_service,
    update_user_service,
    delete_user_service,
    reset_password_service,
)

router = APIRouter()

@router.post("/", response_model=User)
def create_user_endpoint(
    user: UserBase,
    background_tasks: BackgroundTasks,
    db: database.MongoDB = Depends(database.get_mongo_db)
):
    """
    Creates a new user after verifying email code and then sends a welcome email.
    Returns a JSONResponse with a secure JWT set as a cookie.
    """
    result = create_user_service(user, background_tasks, db)
    response = JSONResponse(content={"message": "User created successfully", "user": result["user_data"]})
    response.set_cookie(
        key="Authorization",
        value=f"Bearer {result['token']}",
        httponly=True,
        max_age=180000,
        expires=180000,
        path="/",
        secure=True,
        samesite="None"
    )
    return response

#This is for sending email verification, this doesnt requires basic auth
@router.post("/emailverification/")
def send_email_verification(
    email_action: EmailAction,
    background_tasks: BackgroundTasks,
    db: database.MongoDB = Depends(database.get_mongo_db)
):
    """
    Sends a verification code via email for signup, forgot password, or invite actions.
    """
    return send_email_verification_service(email_action, background_tasks, db)

#This is for sending invitation, this requires basic auth
@router.post("/invite/")
def send_invite(
    email_action: EmailAction,
    background_tasks: BackgroundTasks,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: User = Depends(get_current_userdetails)
):
    """
    Sends a verification code via email for signup, forgot password, or invite actions.
    """
    return send_email_verification_service(email_action, background_tasks, db, current_user)

@router.get("/list/", response_model=UserResponseList)
def get_users(
    skip: int = 0,
    limit: int = 10,
    q: Optional[str] = None,
    is_active: Optional[bool] = None,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: User = Depends(get_current_userdetails)
):
    """
    Returns a list of users for the given account.
    """
    account_id = current_user.get("account_id")

    return get_users_service(account_id, skip, limit, q, is_active, db, current_user)

@router.get("/list/all/", response_model=UserResponseList)
def get_users(
    skip: int = 0,
    limit: int = 10,
    q: Optional[str] = None,
    is_active: Optional[bool] = None,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: User = Depends(get_current_userdetails)
):
    """
    Returns a list of users for the given account.
    """
    account_id = 'all'
    
    return get_users_service(account_id, skip, limit, q, is_active, db, current_user)

@router.get("/{user_id}", response_model=User)
def read_user(
    user_id: str,
    db: database.MongoDB = Depends(database.get_mongo_db)
):
    """
    Returns user details by user ID.
    """
    user = read_user_service(user_id, db)
    if user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return user

@router.put("/{user_id}", response_model=User)
def update_user(
    user_id: str,
    user_data: UserUpdate,
    db: database.MongoDB = Depends(database.get_mongo_db)
):
    """
    Updates user information.
    """
    updated_user = update_user_service(user_id, user_data, db)
    if updated_user is None:
        raise HTTPException(status_code=404, detail="User not found after update")
    return updated_user

@router.delete("/{user_id}", response_model=User)
def delete_user(
    user_id: str = Path(..., description="The ID of the user"),
    db: database.MongoDB = Depends(database.get_mongo_db)
):
    """
    Deletes a user by ID.
    """
    user = delete_user_service(user_id, db)
    if user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return user

@router.post("/reset-password/")
def reset_password(
    request_body: ResetPasswordRequest,
    db: database.MongoDB = Depends(database.get_mongo_db)
):
    """
    Resets a user's password after verifying the provided code.
    """
    return reset_password_service(request_body, db)
