import "server-only";

import { Query } from "node-appwrite";

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

export async function listJobHistory(jobId: string): Promise<JobStatusHistory[]> {
  const { tablesDB } = createAdminClient();
  const result = await tablesDB.listRows({
    databaseId: DATABASE_ID,
    tableId: TABLES.jobStatusHistory,
    queries: [
      Query.equal("jobId", jobId),
      Query.orderAsc("completedAt"),
      Query.limit(100),
    ],
  });
  return toPlain(result.rows as unknown as JobStatusHistory[]);
}
