"""Auth API routes — Google SSO login and user info."""

from __future__ import annotations

from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel

from core.auth import verify_google_token, find_or_create_user, create_jwt
from api.deps import get_current_user

router = APIRouter()


class GoogleLoginRequest(BaseModel):
    id_token: str


@router.post("/google")
def login_google(body: GoogleLoginRequest):
    """Verify Google ID token and return JWT + user info."""
    try:
        google_info = verify_google_token(body.id_token)
    except ValueError as e:
        raise HTTPException(401, f"Invalid Google token: {e}")

    user = find_or_create_user(
        provider="google",
        provider_id=google_info["sub"],
        email=google_info.get("email"),
        nickname=google_info.get("name"),
        avatar_url=google_info.get("picture"),
    )
    access_token = create_jwt(user)
    return {"access_token": access_token, "user": user}


@router.get("/me")
def get_me(current_user: dict = Depends(get_current_user)):
    """Return current authenticated user info including admin status."""
    from core.db import conn
    user_id = current_user.get("sub") or current_user.get("id")
    with conn() as c:
        cur = c.cursor()
        cur.execute(
            "SELECT id, email, nickname, avatar_url, is_admin FROM tasteby_users WHERE id = :id",
            {"id": user_id},
        )
        row = cur.fetchone()
        if not row:
            raise HTTPException(404, "User not found")
        return {
            "id": row[0],
            "email": row[1],
            "nickname": row[2],
            "avatar_url": row[3],
            "is_admin": bool(row[4]),
        }
