from fastapi import APIRouter, status, HTTPException, Depends
from app.database import get_database
from app.repositories.agent_repository import get_agent_by_email
from app.utils.security import verify_password, create_access_token
from app.models.auth import AgentLoginRequest, AgentLoginResponse, SafeAgentInfo
from app.dependencies.auth import get_current_agent

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

@router.post("/login", response_model=AgentLoginResponse, status_code=status.HTTP_200_OK)
async def login_agent(payload: AgentLoginRequest):
    """
    Authenticates an agent using email and password.
    Returns a JWT access token and safe agent profile info.
    Generic 401 Unauthorized returned on invalid credentials.
    """
    db = get_database()
    agent = await get_agent_by_email(db, payload.email)

    # Generic authentication error to avoid user enumeration
    generic_error = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Invalid email or password",
        headers={"WWW-Authenticate": "Bearer"},
    )

    if not agent or agent.get("status") != "ACTIVE":
        raise generic_error

    password_hash = agent.get("passwordHash", "")
    if not verify_password(payload.password, password_hash):
        raise generic_error

    agent_id = agent["agentId"]
    agent_role = agent.get("role", "AGENT")

    # Issue JWT Access Token
    access_token = create_access_token(data={
        "sub": agent_id,
        "role": agent_role
    })

    safe_info = SafeAgentInfo(
        agentId=agent_id,
        name=agent.get("name", "Agent"),
        email=agent["email"],
        role=agent_role,
        status=agent.get("status", "ACTIVE")
    )

    return AgentLoginResponse(
        accessToken=access_token,
        tokenType="bearer",
        agent=safe_info
    )

@router.get("/me", response_model=SafeAgentInfo, status_code=status.HTTP_200_OK)
async def get_authenticated_agent_profile(current_agent: dict = Depends(get_current_agent)):
    """
    Returns profile information for the currently authenticated agent.
    Requires Bearer token authorization header.
    """
    return SafeAgentInfo(
        agentId=current_agent["agentId"],
        name=current_agent.get("name", "Agent"),
        email=current_agent["email"],
        role=current_agent.get("role", "AGENT"),
        status=current_agent.get("status", "ACTIVE")
    )
