import "server-only";

import { Query } from "node-appwrite";

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

export type JobFileWithUrl = JobFile & {
  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: getFileViewUrl(BUCKETS.jobFiles, r.fileId),
    })),
  );
}
