import { createRoute } from "../../modules/api-utils/createRoute";
import { apiResponse } from "../../modules/api-utils/apiResponse";
import { ContentfulStatusCode } from "hono/utils/http-status";
import { authMiddleware } from "../middleware/authorization";
import { prisma } from "../../constants";

/* GET /v1/cw/sync/status — latest sync job run with step logs */
export const syncStatus = createRoute(
  "get",
  ["/sync/status"],
  async (c) => {
    const latest = await prisma.syncJobRun.findFirst({
      orderBy: { createdAt: "desc" },
      include: {
        steps: {
          orderBy: { createdAt: "asc" },
        },
      },
    });

    if (!latest) {
      const response = apiResponse.successful("No sync runs found", null);
      return c.json(response, response.status as ContentfulStatusCode);
    }

    const response = apiResponse.successful("Latest sync run", latest);
    return c.json(response, response.status as ContentfulStatusCode);
  },
  authMiddleware()
);

/* GET /v1/cw/sync/status/:jobId — specific job details */
export const syncStatusById = createRoute(
  "get",
  ["/sync/status/:jobId"],
  async (c) => {
    const jobId = c.req.param("jobId");

    const run = await prisma.syncJobRun.findUnique({
      where: { id: jobId },
      include: {
        steps: {
          orderBy: { createdAt: "asc" },
        },
      },
    });

    if (!run) {
      const response = apiResponse.notFound("Sync run not found");
      return c.json(response, response.status as ContentfulStatusCode);
    }

    const response = apiResponse.successful("Sync run details", run);
    return c.json(response, response.status as ContentfulStatusCode);
  },
  authMiddleware()
);

/* GET /v1/cw/sync/history — last N sync runs */
export const syncHistory = createRoute(
  "get",
  ["/sync/history"],
  async (c) => {
    const limitParam = c.req.query("limit");
    const limit = Math.min(
      Math.max(Number.parseInt(limitParam || "20", 10) || 20, 1),
      100
    );

    const runs = await prisma.syncJobRun.findMany({
      orderBy: { createdAt: "desc" },
      take: limit,
      include: {
        _count: {
          select: { steps: true },
        },
      },
    });

    const response = apiResponse.successful("Sync history", runs);
    return c.json(response, response.status as ContentfulStatusCode);
  },
  authMiddleware()
);
