import os
from fastapi import Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt

SECRET    = os.environ.get("GUARDIA_JWT_SECRET", "guardia-jwt-secret-2026-change-me!")
ALGORITHM = "HS256"
oauth2    = OAuth2PasswordBearer(tokenUrl="/guardia-api/api/auth/login", auto_error=False)

async def verify_token(token: str = Depends(oauth2)) -> dict:
    if not token:
        raise HTTPException(status_code=401, detail="인증이 필요합니다.")
    try:
        return jwt.decode(token, SECRET, algorithms=[ALGORITHM])
    except JWTError:
        raise HTTPException(status_code=401, detail="유효하지 않은 토큰입니다.")

async def require_admin(payload: dict = Depends(verify_token)) -> dict:
    if payload.get("role") not in ("admin",):
        raise HTTPException(status_code=403, detail="관리자 권한이 필요합니다.")
    return payload
