import "server-only";

import { Query } from "node-appwrite";

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

/**
 * Purge the binary scan/image/document objects backing a finished job from
 * Appwrite Storage and stamp archivedAt on the corresponding rows. The row
 * itself stays — the lab and clinic still need the audit trail (which file
 * was uploaded, by whom, when) long after delivery.
 *
 * Best-effort: a single Storage error must not block the calling action.
 * The function never throws.
 */
export async function archiveJobFiles(jobId: string): Promise<void> {
  const { tablesDB, storage } = createAdminClient();
  try {
    const result = await tablesDB.listRows({
      databaseId: DATABASE_ID,
      tableId: TABLES.jobFiles,
      queries: [Query.equal("jobId", jobId), Query.limit(500)],
    });
    const rows = result.rows as unknown as JobFile[];
    const now = new Date().toISOString();
    await Promise.all(
      rows.map(async (r) => {
        if (r.archivedAt) return;
        try {
          await storage.deleteFile(BUCKETS.jobFiles, r.fileId);
        } catch {
          // file already gone, or storage unreachable — still flip archivedAt
          // so the UI doesn't keep teasing a download button.
        }
        try {
          await tablesDB.updateRow(DATABASE_ID, TABLES.jobFiles, r.$id, {
            archivedAt: now,
          });
        } catch {
          // row update failed; leave it for the next call to retry.
        }
      }),
    );
  } catch {
    // List itself failed — nothing to do.
  }
}
