"""Authenticated file serving — replaces the public StaticFiles mount.

All uploads are private. Every request must carry a valid access_token cookie.
Path traversal is blocked by resolving against UPLOAD_DIR and checking the prefix.
"""

import io
from pathlib import Path

from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.responses import FileResponse, StreamingResponse

from app.dependencies import get_current_user
from app.models.user import User

router = APIRouter()

# Resolved once at import time — safe to use as a prefix check
UPLOAD_DIR = Path("uploads").resolve()


@router.get("/files/gdrive/{file_id}", include_in_schema=False)
async def serve_gdrive_file(
    file_id: str,
    current_user: User = Depends(get_current_user),
) -> StreamingResponse:
    """Proxy a Google Drive file to the authenticated frontend user.

    Fetches from GDrive using the backend service account and streams back.
    This avoids hotlink 403s that occur when the browser requests GDrive directly.
    """
    try:
        from app.utils.gdrive import gdrive_fetch
        content, content_type = gdrive_fetch(file_id)
    except Exception:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="File tidak ditemukan di Google Drive",
        )
    return StreamingResponse(io.BytesIO(content), media_type=content_type)


@router.get("/files/{file_path:path}", include_in_schema=False)
async def serve_file(
    file_path: str,
    current_user: User = Depends(get_current_user),
) -> FileResponse:
    """Serve an uploaded file. Requires a valid session (access_token cookie).

    Path traversal protection: any path that resolves outside UPLOAD_DIR → 403.
    """
    full_path = (UPLOAD_DIR / file_path).resolve()

    # Block path traversal (e.g. ../../etc/passwd)
    if not str(full_path).startswith(str(UPLOAD_DIR) + "/") and full_path != UPLOAD_DIR:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Access denied",
        )

    if not full_path.exists() or not full_path.is_file():
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="File tidak ditemukan",
        )

    return FileResponse(full_path)
