from fastapi import FastAPI, Depends, HTTPException, status, APIRouter, File, UploadFile
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from app.core import security
from app.api import schemas
from app.db import models
from jose import JWTError, jwt
from app.core.security import get_current_user
from fastapi.responses import FileResponse
import os
import uuid
# бд


def get_db():
    db = models.SessionLocal()
    try:
        yield db
    finally:
        db.close()


mediaRouter = APIRouter(
    prefix="/media",
    tags=[],
)

UPLOAD_FOLDER = 'uploads'
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)


@mediaRouter.post('/upload')
async def upload_file(file: UploadFile = File(...)):
    # Проверяем, есть ли файл в запросе
    if not file.filename:
        raise HTTPException(status_code=400, detail="No selected file")

    # Генерируем уникальное имя, чтобы файлы не перезаписывались
    file_id = str(uuid.uuid4())
    filename = f"{file_id}.enc"
    file_path = os.path.join(UPLOAD_FOLDER, filename)

    # Сохраняем
    with open(file_path, "wb") as f:
        content = await file.read()
        f.write(content)

    print(f"Файл сохранен: {file_path}")
    
    return {
        "status": "ok",
        "file_id": file_id
    }


@mediaRouter.get('/{file_id}')
async def get_file(file_id: str):
    filename = f"{file_id}.enc"
    file_path = os.path.join(UPLOAD_FOLDER, filename)

    if not os.path.exists(file_path):
        raise HTTPException(status_code=404, detail="File not found")

    return FileResponse(file_path, media_type="application/octet-stream")