from typing import Any

from fastapi import APIRouter, Body, Depends, Query
from fastapi.responses import StreamingResponse
from sqlalchemy.orm import Session

from core.database import get_core_db
from core.security import get_current_user, validate_access_to_resource

from .schemas import DownloadedPartsReportBootstrap, DownloadedPartsReportRequest
from .service import DownloadedPartsReportService

router = APIRouter(tags=["Reports - Downloaded Parts"])


@router.get(
    "/bootstrap",
    summary="Get downloaded parts report bootstrap",
    description="Returns the base metadata required to render the downloaded parts report screen.",
)
def get_downloaded_parts_report_bootstrap(
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: Any = Depends(get_current_user),
):
    tenant_id = validate_access_to_resource(db, company_id, current_user)
    service = DownloadedPartsReportService()
    return service.build_bootstrap(company_id=company_id, tenant_id=tenant_id)


@router.post(
    "/generate",
    summary="Generate downloaded parts report CSV",
)
def generate_downloaded_parts_report(
    company_id: int = Query(..., description="Company ID"),
    request: DownloadedPartsReportRequest = Body(...),
    db: Session = Depends(get_core_db),
    current_user: Any = Depends(get_current_user),
) -> StreamingResponse:
    tenant_id = validate_access_to_resource(db, company_id, current_user)
    service = DownloadedPartsReportService()
    return service.generate_csv(db=db, req=request, company_id=company_id, tenant_id=tenant_id)
