"""Secure file storage routes for DSCons."""

import os
from pathlib import Path

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

from app.modules.auth.presentation.auth import get_current_user

router = APIRouter(tags=["storage"])

STORAGE_DIR = Path("storage/secure_vault").resolve()
# Ensure directory exists on startup
STORAGE_DIR.mkdir(parents=True, exist_ok=True)

@router.get("/storage/{file_path:path}")
def get_secure_file(
    file_path: str, current_user: dict = Depends(get_current_user)
) -> FileResponse:
    """Serve files securely, requiring user authentication."""
    # Prevent directory traversal
    target_path = (STORAGE_DIR / file_path).resolve()
    
    try:
        # Check if the target path is still inside the STORAGE_DIR
        target_path.relative_to(STORAGE_DIR)
    except ValueError:
        raise HTTPException(status_code=403, detail="Access denied")

    if not target_path.exists() or not target_path.is_file():
        raise HTTPException(status_code=404, detail="File not found")

    return FileResponse(target_path)
