import { NextResponse } from "next/server";
import { z } from "zod";
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
import { readJsonSafe } from "@open-mercato/shared/lib/http/readJsonSafe";
import { readOptimisticLockExpected } from "@open-mercato/shared/lib/crud/optimistic-lock-command";
import { isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
import { updateSyncScheduleSchema } from "../../../data/validators.js";
import { serializeSchedule } from "../serialize.js";
import {
  runCrudMutationGuardAfterSuccess,
  validateCrudMutationGuard
} from "@open-mercato/shared/lib/crud/mutation-guard";
const paramsSchema = z.object({
  id: z.string().uuid()
});
const metadata = {
  GET: { requireAuth: true, requireFeatures: ["data_sync.configure"] },
  PUT: { requireAuth: true, requireFeatures: ["data_sync.configure"] },
  DELETE: { requireAuth: true, requireFeatures: ["data_sync.configure"] }
};
const openApi = {
  tags: ["DataSync"],
  summary: "Manage a sync schedule"
};
async function GET(req, ctx) {
  const auth = await getAuthFromRequest(req);
  if (!auth?.tenantId || !auth.orgId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const rawParams = ctx.params && typeof ctx.params.then === "function" ? await ctx.params : ctx.params;
  const parsedParams = paramsSchema.safeParse(rawParams);
  if (!parsedParams.success) {
    return NextResponse.json({ error: "Invalid schedule id" }, { status: 400 });
  }
  const container = await createRequestContainer();
  const scheduleService = container.resolve("dataSyncScheduleService");
  const schedule = await scheduleService.getById(parsedParams.data.id, {
    organizationId: auth.orgId,
    tenantId: auth.tenantId
  });
  if (!schedule) {
    return NextResponse.json({ error: "Schedule not found" }, { status: 404 });
  }
  return NextResponse.json(serializeSchedule(schedule));
}
async function PUT(req, ctx) {
  const auth = await getAuthFromRequest(req);
  if (!auth?.tenantId || !auth.orgId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const rawParams = ctx.params && typeof ctx.params.then === "function" ? await ctx.params : ctx.params;
  const parsedParams = paramsSchema.safeParse(rawParams);
  if (!parsedParams.success) {
    return NextResponse.json({ error: "Invalid schedule id" }, { status: 400 });
  }
  const payload = await readJsonSafe(req);
  const parsed = updateSyncScheduleSchema.safeParse(payload);
  if (!parsed.success) {
    return NextResponse.json({ error: "Invalid payload", details: parsed.error.flatten() }, { status: 422 });
  }
  const container = await createRequestContainer();
  const scheduleService = container.resolve("dataSyncScheduleService");
  const scope = { organizationId: auth.orgId, tenantId: auth.tenantId };
  const current = await scheduleService.getById(parsedParams.data.id, scope);
  if (!current) {
    return NextResponse.json({ error: "Schedule not found" }, { status: 404 });
  }
  const guardResult = await validateCrudMutationGuard(container, {
    tenantId: auth.tenantId,
    organizationId: scope.organizationId,
    userId: auth.sub,
    resourceKind: "data_sync.schedule",
    resourceId: current.id,
    operation: "update",
    requestMethod: req.method,
    requestHeaders: req.headers,
    mutationPayload: parsed.data
  });
  if (guardResult && !guardResult.ok) {
    return NextResponse.json(guardResult.body, { status: guardResult.status });
  }
  try {
    const schedule = await scheduleService.saveSchedule({
      id: current.id,
      integrationId: parsed.data.integrationId ?? current.integrationId,
      entityType: parsed.data.entityType ?? current.entityType,
      direction: parsed.data.direction ?? current.direction,
      scheduleType: parsed.data.scheduleType ?? current.scheduleType,
      scheduleValue: parsed.data.scheduleValue ?? current.scheduleValue,
      timezone: parsed.data.timezone ?? current.timezone,
      fullSync: parsed.data.fullSync ?? current.fullSync,
      isEnabled: parsed.data.isEnabled ?? current.isEnabled,
      expectedUpdatedAt: readOptimisticLockExpected(req)
    }, scope, container);
    if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {
      await runCrudMutationGuardAfterSuccess(container, {
        tenantId: auth.tenantId,
        organizationId: scope.organizationId,
        userId: auth.sub,
        resourceKind: "data_sync.schedule",
        resourceId: schedule.id,
        operation: "update",
        requestMethod: req.method,
        requestHeaders: req.headers,
        metadata: guardResult.metadata ?? null
      });
    }
    return NextResponse.json(serializeSchedule(schedule));
  } catch (error) {
    if (isCrudHttpError(error)) {
      return NextResponse.json(error.body, { status: error.status });
    }
    const message = error instanceof Error ? error.message : "Failed to update sync schedule";
    return NextResponse.json({ error: message }, { status: 422 });
  }
}
async function DELETE(req, ctx) {
  const auth = await getAuthFromRequest(req);
  if (!auth?.tenantId || !auth.orgId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const rawParams = ctx.params && typeof ctx.params.then === "function" ? await ctx.params : ctx.params;
  const parsedParams = paramsSchema.safeParse(rawParams);
  if (!parsedParams.success) {
    return NextResponse.json({ error: "Invalid schedule id" }, { status: 400 });
  }
  const container = await createRequestContainer();
  const scheduleService = container.resolve("dataSyncScheduleService");
  const scope = { organizationId: auth.orgId, tenantId: auth.tenantId };
  const guardResult = await validateCrudMutationGuard(container, {
    tenantId: auth.tenantId,
    organizationId: scope.organizationId,
    userId: auth.sub,
    resourceKind: "data_sync.schedule",
    resourceId: parsedParams.data.id,
    operation: "delete",
    requestMethod: req.method,
    requestHeaders: req.headers,
    mutationPayload: null
  });
  if (guardResult && !guardResult.ok) {
    return NextResponse.json(guardResult.body, { status: guardResult.status });
  }
  try {
    const deleted = await scheduleService.deleteSchedule(
      parsedParams.data.id,
      scope,
      container,
      readOptimisticLockExpected(req)
    );
    if (!deleted) {
      return NextResponse.json({ error: "Schedule not found" }, { status: 404 });
    }
    if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {
      await runCrudMutationGuardAfterSuccess(container, {
        tenantId: auth.tenantId,
        organizationId: scope.organizationId,
        userId: auth.sub,
        resourceKind: "data_sync.schedule",
        resourceId: parsedParams.data.id,
        operation: "delete",
        requestMethod: req.method,
        requestHeaders: req.headers,
        metadata: guardResult.metadata ?? null
      });
    }
    return NextResponse.json({ deleted: true });
  } catch (error) {
    if (isCrudHttpError(error)) {
      return NextResponse.json(error.body, { status: error.status });
    }
    const message = error instanceof Error ? error.message : "Failed to delete sync schedule";
    return NextResponse.json({ error: message }, { status: 422 });
  }
}
export {
  DELETE,
  GET,
  PUT,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
