import {
  ackWorkItem,
  getWorkItem,
  getWorkQueueStats,
  heartbeatWorkItem,
  listWorkItems,
  pollWorkItem,
  stopWorkItem,
  updateWorkItemMetadata
} from "./chunk-EDM5KER5.js";
import {
  decodeCursor,
  jsonOk,
  paginatedOk,
  routeWrap
} from "./chunk-ZMMFMEXX.js";
import {
  getEnvironment
} from "./chunk-GTYDSYTR.js";
import {
  badRequest,
  notFound
} from "./chunk-EZYKRG4W.js";

// src/handlers/work.ts
import { z } from "zod";
function assertSelfHostedEnv(envId) {
  const env = getEnvironment(envId);
  if (!env) throw notFound(`environment not found: ${envId}`);
  if (env.config?.type !== "self_hosted")
    throw badRequest("work queue is only available on self_hosted environments");
  return env;
}
function handleListWork(request, envId) {
  return routeWrap(request, async ({ request: req }) => {
    assertSelfHostedEnv(envId);
    const url = new URL(req.url);
    const requestedLimit = Number(url.searchParams.get("limit") || "20");
    const cursor = decodeCursor(url.searchParams.get("after_id") ?? url.searchParams.get("page"));
    const state = url.searchParams.get("state") ?? void 0;
    const items = listWorkItems(envId, { limit: requestedLimit, cursor, state });
    return paginatedOk(items, requestedLimit);
  });
}
function handleGetWork(request, envId, workId) {
  return routeWrap(request, async () => {
    assertSelfHostedEnv(envId);
    const item = getWorkItem(workId);
    if (!item || item.environment_id !== envId) throw notFound(`work item not found: ${workId}`);
    return jsonOk(item);
  });
}
var UpdateWorkSchema = z.object({
  metadata: z.record(z.union([z.string(), z.null()]))
});
function handleUpdateWork(request, envId, workId) {
  return routeWrap(request, async () => {
    assertSelfHostedEnv(envId);
    const body = await request.json();
    const parsed = UpdateWorkSchema.safeParse(body);
    if (!parsed.success) throw badRequest(parsed.error.message);
    const item = updateWorkItemMetadata(workId, parsed.data.metadata);
    if (!item || item.environment_id !== envId) throw notFound(`work item not found: ${workId}`);
    return jsonOk(item);
  });
}
function handlePollWork(request, envId) {
  return routeWrap(request, async ({ request: req }) => {
    assertSelfHostedEnv(envId);
    const url = new URL(req.url);
    const workerId = url.searchParams.get("worker_id") ?? void 0;
    const item = pollWorkItem(envId, workerId);
    if (!item) return jsonOk({ data: null });
    return jsonOk(item);
  });
}
function handleWorkStats(request, envId) {
  return routeWrap(request, async () => {
    assertSelfHostedEnv(envId);
    const stats = getWorkQueueStats(envId);
    return jsonOk(stats);
  });
}
var AckWorkSchema = z.object({
  worker_id: z.string().optional()
}).optional();
function handleAckWork(request, envId, workId) {
  return routeWrap(request, async () => {
    assertSelfHostedEnv(envId);
    let workerId;
    try {
      const body = await request.json();
      const parsed = AckWorkSchema.safeParse(body);
      if (parsed.success && parsed.data) {
        workerId = parsed.data.worker_id;
      }
    } catch {
    }
    const item = ackWorkItem(workId, workerId);
    if (!item) throw notFound(`work item not found or not in pending state: ${workId}`);
    if (item.environment_id !== envId) throw notFound(`work item not found: ${workId}`);
    return jsonOk(item);
  });
}
function handleHeartbeatWork(request, envId, workId) {
  return routeWrap(request, async () => {
    assertSelfHostedEnv(envId);
    const existing = getWorkItem(workId);
    if (!existing || existing.environment_id !== envId)
      throw notFound(`work item not found: ${workId}`);
    const result = heartbeatWorkItem(workId);
    if (!result) throw notFound(`work item not found: ${workId}`);
    return jsonOk(result);
  });
}
var StopWorkSchema = z.object({
  force: z.boolean().optional()
}).optional();
function handleStopWork(request, envId, workId) {
  return routeWrap(request, async () => {
    assertSelfHostedEnv(envId);
    let force;
    try {
      const body = await request.json();
      const parsed = StopWorkSchema.safeParse(body);
      if (parsed.success && parsed.data) {
        force = parsed.data.force;
      }
    } catch {
    }
    const item = stopWorkItem(workId, force);
    if (!item || item.environment_id !== envId) throw notFound(`work item not found: ${workId}`);
    return jsonOk(item);
  });
}

export {
  handleListWork,
  handleGetWork,
  handleUpdateWork,
  handlePollWork,
  handleWorkStats,
  handleAckWork,
  handleHeartbeatWork,
  handleStopWork
};
