import type { Request, Response } from 'express';
import { paramStr } from '@/api/http/request';
import services from '@/services/file';
import { assertCanDownloadFile } from '@/services/file-access';

export async function download(req: Request, res: Response): Promise<void> {
  // Enforce per-file tenant ownership before serving the path (Workstream 3
  // §3.5 / file workstream). Throws ForbiddenError on a cross-tenant fetch.
  const privateUrl = String(req.query.privateUrl ?? '');
  await assertCanDownloadFile(privateUrl, req.currentUser);

  if (process.env.NODE_ENV === 'production' || process.env.NEXT_PUBLIC_BACK_API) {
    void services.downloadGCloud(req, res);
  } else {
    services.downloadLocal(req, res);
  }
}

export function upload(req: Request, res: Response): void {
  const fileName = `${paramStr(req.params.table)}/${paramStr(req.params.field)}`;

  if (
    process.env.NODE_ENV === 'production' ||
    process.env.NEXT_PUBLIC_BACK_API
  ) {
    void services.uploadGCloud(fileName, req, res);
  } else {
    void services.uploadLocal(fileName, {
      entity: null,
      maxFileSize: 10 * 1024 * 1024,
      folderIncludesAuthenticationUid: false,
    })(req, res);
  }
}
