import os
import uuid

from fastapi import APIRouter, Depends, File, Form, Request, UploadFile
from fastapi.responses import FileResponse, RedirectResponse
from sqlalchemy.orm import Session

from config import UPLOAD_DIR
from dependencies import get_current_user, get_db
from models.dokument import Dokument

router = APIRouter(prefix="/dokumente")

UPLOAD_DIR.mkdir(parents=True, exist_ok=True)


@router.post("/upload")
async def upload(
    datei: UploadFile = File(...),
    kontakt_id: int = Form(None),
    aktivitaet_id: int = Form(None),
    veranstaltung_id: int = Form(None),
    beschreibung: str = Form(None),
    user=Depends(get_current_user),
    db: Session = Depends(get_db),
):
    ext = os.path.splitext(datei.filename)[1]
    unique_name = f"{uuid.uuid4().hex}{ext}"
    file_path = UPLOAD_DIR / unique_name

    content = await datei.read()
    with open(file_path, "wb") as f:
        f.write(content)

    dok = Dokument(
        kontakt_id=kontakt_id,
        aktivitaet_id=aktivitaet_id,
        veranstaltung_id=veranstaltung_id,
        dateiname=datei.filename,
        dateipfad=str(file_path),
        dateityp=datei.content_type,
        dateigroesse=len(content),
        beschreibung=beschreibung,
        erfasst_von=user.kuerzel,
    )
    db.add(dok)
    db.commit()

    redirect_url = "/"
    if kontakt_id:
        redirect_url = f"/kontakte/{kontakt_id}"
    return RedirectResponse(url=redirect_url, status_code=303)


@router.get("/{dok_id}/download")
async def download(dok_id: int, user=Depends(get_current_user), db: Session = Depends(get_db)):
    dok = db.query(Dokument).filter(Dokument.id == dok_id).first()
    if not dok or not os.path.exists(dok.dateipfad):
        return RedirectResponse(url="/", status_code=303)
    return FileResponse(dok.dateipfad, filename=dok.dateiname)
