import type { LoaderFunctionArgs } from "@remix-run/node";
import { json } from "@remix-run/node";

import { authenticate } from "../shopify.server";
import db from "../db.server";

/**
 * GET /api/jobs/:id
 *
 * Returns the BackgroundJob row by id. Scoped to the authenticated shop —
 * a merchant cannot read another shop's jobs even if they guess the cuid.
 */
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
  const { session } = await authenticate.admin(request);
  const id = params.id;
  if (!id) {
    return json({ error: "Missing job id" }, { status: 400 });
  }

  const row = await db.backgroundJob.findUnique({ where: { id } });
  if (!row || row.shopId !== session.shop) {
    return json({ error: "Not found" }, { status: 404 });
  }

  return json({
    id: row.id,
    type: row.type,
    status: row.status,
    attempts: row.attempts,
    lastError: row.lastError,
    businessResult: row.businessResult,
    createdAt: row.createdAt.toISOString(),
    completedAt: row.completedAt?.toISOString() ?? null,
  });
};
