from fastapi import Depends, File, UploadFile, APIRouter
from sqlalchemy.ext.asyncio import AsyncSession
from starlette.responses import FileResponse

from app.database.session import get_db
from app.domain.entities.appointment_file import AppointmentFileEntity
from app.infrastructure.appointment_files_service import AppointmentFilesService
from app.infrastructure.dependencies import get_current_user

router = APIRouter()


@router.get(
    '/{appointment_id}/',
    response_model=list[AppointmentFileEntity],
    summary='Get all appointment files',
    description='Returns metadata of all files uploaded for the specified appointment.'
)
async def get_files_by_project_id(
        appointment_id: int,
        db: AsyncSession = Depends(get_db),
        user=Depends(get_current_user),
):
    appointment_files_service = AppointmentFilesService(db)
    return await appointment_files_service.get_files_by_appointment_id(appointment_id, user)


@router.get(
    '/{file_id}/file/',
    response_class=FileResponse,
    summary='Download appointment file by ID',
    description='Returns the file for the specified file ID.'
)
async def download_project_file(
        file_id: int,
        db: AsyncSession = Depends(get_db),
        user=Depends(get_current_user),
):
    appointment_files_service = AppointmentFilesService(db)
    return await appointment_files_service.get_file_by_id(file_id, user)


@router.post(
    '/{appointment_id}/upload/',
    response_model=AppointmentFileEntity,
    summary='Upload a new file for the appointment',
    description='Uploads a new file and associates it with the specified appointment.'
)
async def upload_project_file(
        appointment_id: int,
        file: UploadFile = File(...),
        db: AsyncSession = Depends(get_db),
        user=Depends(get_current_user),
):
    appointment_files_service = AppointmentFilesService(db)
    return await appointment_files_service.upload_file(appointment_id, file, user)


@router.delete(
    '/{file_id}/',
    response_model=AppointmentFileEntity,
    summary='Delete an appointment file by ID',
    description='Deletes the file and its database entry.'
)
async def delete_project_file(
        file_id: int,
        db: AsyncSession = Depends(get_db),
        user=Depends(get_current_user),
):
    appointment_files_service = AppointmentFilesService(db)
    return await appointment_files_service.delete_file(file_id, user)
