import { computeNextFireAt } from './chunk-XEXUQSKG.js';
import { listSchedulesResponseSchema, listSchedulesQuerySchema, scheduleResponseSchema, scheduleIdPathParams, listScheduleTriggersResponseSchema, listScheduleTriggersQuerySchema } from './chunk-4HFIGLPA.js';
import { createRoute } from './chunk-PIKPS6Q6.js';
import { HTTPException } from './chunk-6QWQZI4Q.js';

// src/server/handlers/schedules.ts
function snapshotToRunSummary(run) {
  const snapshot = typeof run.snapshot === "string" ? null : run.snapshot;
  if (!snapshot) return void 0;
  const startedAt = run.createdAt instanceof Date ? run.createdAt.getTime() : void 0;
  const isTerminal = snapshot.status === "success" || snapshot.status === "failed" || snapshot.status === "canceled" || snapshot.status === "bailed" || snapshot.status === "tripwire";
  const completedAt = isTerminal ? run.updatedAt instanceof Date ? run.updatedAt.getTime() : void 0 : void 0;
  const durationMs = startedAt !== void 0 && completedAt !== void 0 ? completedAt - startedAt : void 0;
  return {
    status: snapshot.status,
    startedAt,
    completedAt,
    durationMs,
    error: snapshot.error?.message
  };
}
async function fetchRunSummary(mastra, workflowName, runId) {
  try {
    const workflowsStore = await mastra.getStorage()?.getStore("workflows");
    const run = await workflowsStore?.getWorkflowRunById({ runId, workflowName });
    if (!run) return void 0;
    return snapshotToRunSummary(run);
  } catch {
    return void 0;
  }
}
async function hydrateScheduleResponse(mastra, schedule) {
  if (!schedule.lastRunId || schedule.target.type !== "workflow" || !schedule.target.workflowId) {
    return schedule;
  }
  const lastRun = await fetchRunSummary(mastra, schedule.target.workflowId, schedule.lastRunId);
  return lastRun ? { ...schedule, lastRun } : schedule;
}
var LIST_SCHEDULES_ROUTE = createRoute({
  method: "GET",
  path: "/schedules",
  responseType: "json",
  queryParamSchema: listSchedulesQuerySchema,
  responseSchema: listSchedulesResponseSchema,
  summary: "List workflow schedules",
  description: "Returns the configured schedules, optionally filtered by workflowId or status.",
  tags: ["Schedules"],
  requiresAuth: true,
  handler: async ({ mastra, workflowId, status, ownerType, ownerId }) => {
    const schedulesStore = await mastra.getStorage()?.getStore("schedules");
    if (!schedulesStore) {
      return { schedules: [] };
    }
    const schedules = await schedulesStore.listSchedules({ workflowId, status, ownerType, ownerId });
    const visible = ownerType !== void 0 || ownerId !== void 0 ? schedules : schedules.filter((s) => s.ownerType == null);
    const hydrated = await Promise.all(
      visible.map(async (schedule) => {
        if (!schedule.lastRunId || schedule.target.type !== "workflow") {
          return schedule;
        }
        const lastRun = await fetchRunSummary(mastra, schedule.target.workflowId, schedule.lastRunId);
        return lastRun ? { ...schedule, lastRun } : schedule;
      })
    );
    return { schedules: hydrated };
  }
});
var GET_SCHEDULE_ROUTE = createRoute({
  method: "GET",
  path: "/schedules/:scheduleId",
  responseType: "json",
  pathParamSchema: scheduleIdPathParams,
  responseSchema: scheduleResponseSchema,
  summary: "Get a workflow schedule by ID",
  description: "Returns a single schedule row by its storage id.",
  tags: ["Schedules"],
  requiresAuth: true,
  handler: async ({ mastra, scheduleId }) => {
    const schedulesStore = await mastra.getStorage()?.getStore("schedules");
    if (!schedulesStore) {
      throw new HTTPException(404, { message: "Schedule not found" });
    }
    const schedule = await schedulesStore.getSchedule(scheduleId);
    if (!schedule) {
      throw new HTTPException(404, { message: "Schedule not found" });
    }
    return hydrateScheduleResponse(mastra, schedule);
  }
});
var LIST_SCHEDULE_TRIGGERS_ROUTE = createRoute({
  method: "GET",
  path: "/schedules/:scheduleId/triggers",
  responseType: "json",
  pathParamSchema: scheduleIdPathParams,
  queryParamSchema: listScheduleTriggersQuerySchema,
  responseSchema: listScheduleTriggersResponseSchema,
  summary: "List trigger history for a schedule",
  description: "Returns the audit trail of trigger attempts for a schedule, ordered by actualFireAt descending.",
  tags: ["Schedules"],
  requiresAuth: true,
  handler: async ({ mastra, scheduleId, limit, fromActualFireAt, toActualFireAt }) => {
    const schedulesStore = await mastra.getStorage()?.getStore("schedules");
    if (!schedulesStore) {
      return { triggers: [] };
    }
    const schedule = await schedulesStore.getSchedule(scheduleId);
    const triggers = await schedulesStore.listTriggers(scheduleId, { limit, fromActualFireAt, toActualFireAt });
    if (!schedule || schedule.target.type !== "workflow") {
      return { triggers };
    }
    const workflowName = schedule.target.workflowId;
    const hydrated = await Promise.all(
      triggers.map(async (trigger) => {
        if (trigger.outcome !== "published" || !trigger.runId) return trigger;
        const run = await fetchRunSummary(mastra, workflowName, trigger.runId);
        return run ? { ...trigger, run } : trigger;
      })
    );
    return { triggers: hydrated };
  }
});
var PAUSE_SCHEDULE_ROUTE = createRoute({
  method: "POST",
  path: "/schedules/:scheduleId/pause",
  responseType: "json",
  pathParamSchema: scheduleIdPathParams,
  responseSchema: scheduleResponseSchema,
  summary: "Pause a workflow schedule",
  description: "Marks the schedule as paused. The scheduler tick loop will skip paused schedules. Idempotent \u2014 pausing an already-paused schedule returns the current state unchanged. Pause status survives redeploys.",
  tags: ["Schedules"],
  requiresAuth: true,
  handler: async ({ mastra, scheduleId }) => {
    const schedulesStore = await mastra.getStorage()?.getStore("schedules");
    if (!schedulesStore) {
      throw new HTTPException(404, { message: "Schedule not found" });
    }
    const existing = await schedulesStore.getSchedule(scheduleId);
    if (!existing) {
      throw new HTTPException(404, { message: "Schedule not found" });
    }
    if (existing.status === "paused") {
      return hydrateScheduleResponse(mastra, existing);
    }
    const updated = await schedulesStore.updateSchedule(scheduleId, { status: "paused" });
    return hydrateScheduleResponse(mastra, updated);
  }
});
var RESUME_SCHEDULE_ROUTE = createRoute({
  method: "POST",
  path: "/schedules/:scheduleId/resume",
  responseType: "json",
  pathParamSchema: scheduleIdPathParams,
  responseSchema: scheduleResponseSchema,
  summary: "Resume a paused workflow schedule",
  description: 'Marks the schedule as active and recomputes nextFireAt from "now" so a long-paused schedule does not fire a backlog. Idempotent \u2014 resuming an already-active schedule returns the current state unchanged.',
  tags: ["Schedules"],
  requiresAuth: true,
  handler: async ({ mastra, scheduleId }) => {
    const schedulesStore = await mastra.getStorage()?.getStore("schedules");
    if (!schedulesStore) {
      throw new HTTPException(404, { message: "Schedule not found" });
    }
    const existing = await schedulesStore.getSchedule(scheduleId);
    if (!existing) {
      throw new HTTPException(404, { message: "Schedule not found" });
    }
    if (existing.status === "active") {
      return hydrateScheduleResponse(mastra, existing);
    }
    const nextFireAt = computeNextFireAt(existing.cron, {
      timezone: existing.timezone,
      after: Date.now()
    });
    const updated = await schedulesStore.updateSchedule(scheduleId, { status: "active", nextFireAt });
    return hydrateScheduleResponse(mastra, updated);
  }
});

export { GET_SCHEDULE_ROUTE, LIST_SCHEDULES_ROUTE, LIST_SCHEDULE_TRIGGERS_ROUTE, PAUSE_SCHEDULE_ROUTE, RESUME_SCHEDULE_ROUTE };
//# sourceMappingURL=chunk-RCXVCPAD.js.map
//# sourceMappingURL=chunk-RCXVCPAD.js.map