import { NextResponse } from "next/server";
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
import { listSyncRunsQuerySchema } from "../data/validators.js";
const metadata = {
  GET: { requireAuth: true, requireFeatures: ["data_sync.view"] }
};
const openApi = {
  tags: ["DataSync"],
  summary: "List sync runs"
};
async function GET(req) {
  const auth = await getAuthFromRequest(req);
  if (!auth?.tenantId || !auth.orgId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const url = new URL(req.url);
  const parsed = listSyncRunsQuerySchema.safeParse({
    integrationId: url.searchParams.get("integrationId") ?? void 0,
    entityType: url.searchParams.get("entityType") ?? void 0,
    direction: url.searchParams.get("direction") ?? void 0,
    status: url.searchParams.get("status") ?? void 0,
    search: url.searchParams.get("search") ?? void 0,
    page: url.searchParams.get("page") ?? void 0,
    pageSize: url.searchParams.get("pageSize") ?? void 0
  });
  if (!parsed.success) {
    return NextResponse.json({ error: "Invalid query", details: parsed.error.flatten() }, { status: 400 });
  }
  const container = await createRequestContainer();
  const syncRunService = container.resolve("dataSyncRunService");
  const { items, total } = await syncRunService.listRuns(parsed.data, {
    organizationId: auth.orgId,
    tenantId: auth.tenantId
  });
  return NextResponse.json({
    items: items.map((item) => ({
      id: item.id,
      integrationId: item.integrationId,
      entityType: item.entityType,
      direction: item.direction,
      status: item.status,
      cursor: item.cursor ?? null,
      initialCursor: item.initialCursor ?? null,
      createdCount: item.createdCount,
      updatedCount: item.updatedCount,
      skippedCount: item.skippedCount,
      failedCount: item.failedCount,
      batchesCompleted: item.batchesCompleted,
      lastError: item.lastError ?? null,
      progressJobId: item.progressJobId ?? null,
      triggeredBy: item.triggeredBy ?? null,
      createdAt: item.createdAt.toISOString(),
      updatedAt: item.updatedAt.toISOString()
    })),
    total,
    page: parsed.data.page,
    pageSize: parsed.data.pageSize,
    totalPages: Math.max(1, Math.ceil(total / parsed.data.pageSize))
  });
}
export {
  GET,
  metadata,
  openApi
};
//# sourceMappingURL=runs.js.map
