from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi.responses import JSONResponse, RedirectResponse
from db.schemas import Settings
from utils import logger, render, requestDict
from .settings import router as settingsRouter
from .staff import router as staffRouter


async def require_auth(request: Request):
    # login и статика — без проверки
    if request.url.path.startswith(("/login", "/static")):
        return

    auth_token = request.cookies.get("auth_token")

    # 1️⃣ Нет токена → сразу на логин
    if not auth_token:
        raise HTTPException(status_code=302, headers={"Location": "/login"})

    # 2️⃣ Токен есть → проверяем
    token_check = await Settings.verifyToken(auth_token)

    # 3️⃣ Токен НЕ валиден → удаляем cookie и редирект
    if not token_check.success:
        response = RedirectResponse(url="/login", status_code=302)
        response.delete_cookie(key="auth_token", path="/")
        return response  # ← ВАЖНО: return, не raise

    # 4️⃣ Токен валиден → пропускаем
    return


router = APIRouter(dependencies=[Depends(require_auth)])

router.include_router(settingsRouter, prefix="/settings", tags=["Settings"])
router.include_router(staffRouter, prefix="/staff", tags=["Staff"])


@router.get("/", name="Main", summary="Главная страница")
async def mainPage(request: Request):
    return await render(request)


@router.get("/login", name="Authentication", summary="Авторизация пользователя")
async def authenticationPage(request: Request):
    return await render(request)


@router.post("/login", summary="Authentication")
async def authentication(
    reqData: dict = Depends(requestDict),
):
    logger.info("📥 Получен запрос на /login")

    password = reqData.get("body", {}).get("password", "")
    authSuccess = await Settings.verifyPassword(password)

    if not authSuccess.success:
        return JSONResponse(
            status_code=401, content={"status": "error", "message": "Неверный пароль"}
        )

    response = JSONResponse(content={"status": "ok"})

    response.set_cookie(
        key="auth_token",
        value=authSuccess.data,
        httponly=True,
        secure=False,  # ⚠️ True в HTTPS
        samesite="lax",
        max_age=60 * 60 * 24 * 365,  # 1 год
        path="/",
    )

    logger.info("✅ Пользователь авторизован, cookie установлена")
    return response


@router.get("/logout", summary="Logout")
async def logout():
    response = RedirectResponse(url="/login", status_code=302)
    response.delete_cookie(key="auth_token", path="/")
    await Settings.clearToken()
    return response
