import FileDBApi from '@/db/api/file';
import ForbiddenError from '@/shared/errors/forbidden';
import { getOrganizationId, hasGlobalAccess } from '@/services/shared/access';
import type { CurrentUser } from '@/db/api/types';

/**
 * Per-file tenant/ownership check for downloads (Workstream 3 §3.5 / file
 * workstream). Downloads serve a file by its `privateUrl` path; without this an
 * authenticated user of one tenant could fetch another tenant's file by knowing
 * (or guessing) the path. Global-access (system) roles bypass; everyone else may
 * only fetch a file owned by their own organization. Files with no tracked row
 * are denied by default.
 *
 * Kept out of `services/file.ts` (which is coupled to Express req/res streaming)
 * to avoid a circular dependency with `db/api/file.ts`.
 */
export async function assertCanDownloadFile(
  privateUrl: string,
  currentUser?: CurrentUser,
): Promise<void> {
  if (!currentUser?.id) {
    throw new ForbiddenError();
  }
  if (hasGlobalAccess(currentUser)) {
    return;
  }

  const { found, organizationId } =
    await FileDBApi.findOwnerOrganizationIdByPrivateUrl(privateUrl);

  const requesterOrganizationId = getOrganizationId(currentUser);
  if (!found || !organizationId || organizationId !== requesterOrganizationId) {
    throw new ForbiddenError();
  }
}
