import "server-only";

import { Query } from "node-appwrite";

import { DATABASE_ID, TABLES, type JobFile } from "./schema";
import { createAdminClient } from "./server";
import { toPlain } from "./serialize";

export type JobFileWithUrl = JobFile & {
  /** Server-side download proxy. Browser → our app → admin SDK → bucket. */
  url: string;
};

export async function listJobFiles(jobId: string): Promise<JobFileWithUrl[]> {
  const { tablesDB } = createAdminClient();
  const result = await tablesDB.listRows({
    databaseId: DATABASE_ID,
    tableId: TABLES.jobFiles,
    queries: [
      Query.equal("jobId", jobId),
      Query.orderDesc("$createdAt"),
      Query.limit(200),
    ],
  });
  const rows = result.rows as unknown as JobFile[];
  return toPlain(
    rows.map((r) => ({
      ...r,
      url: `/api/jobs/${jobId}/files/${r.$id}/download`,
    })),
  );
}
