import { apiFormRequest, createApiUrl } from '@/shared/api/httpClient';

function fileUrl(path: string): string {
  return createApiUrl(path);
}

function safeName(name: string): string {
  return name.replace(/[^a-zA-Z0-9._-]/g, '-');
}

/**
 * Uploads a file to `table/field` and returns its private URL
 * (`table/field/filename`) for storage in a logo/avatar field. Multipart upload
 * (the API expects a `file` part plus a `filename`); auth is the session cookie.
 */
export async function uploadFile(
  table: string,
  field: string,
  file: File,
): Promise<string> {
  const filename = `${Date.now()}-${safeName(file.name)}`;
  const form = new FormData();
  form.append('file', file);
  form.append('filename', filename);

  const response = await apiFormRequest(`/file/upload/${table}/${field}`, form);

  if (!response.ok) {
    throw new Error('File upload failed');
  }

  return `${table}/${field}/${filename}`;
}

/** Authenticated download URL usable directly as an <img src>. */
export function fileDownloadUrl(privateUrl: string): string {
  return fileUrl(`/file/download?privateUrl=${encodeURIComponent(privateUrl)}`);
}

export function fileAssetUrl(value: string): string {
  if (
    value.startsWith('/')
    || value.startsWith('http://')
    || value.startsWith('https://')
    || value.startsWith('data:')
    || value.startsWith('blob:')
  ) {
    return value;
  }

  return fileDownloadUrl(value);
}
