import { FastifyInstance } from "fastify";
import { ScanScheduler } from "@shieldai/darkwatch";

export function schedulerRoutes(fastify: FastifyInstance) {
  const scheduler = new ScanScheduler();

  fastify.post(
    "/ensure",
    async (request, reply) => {
      const userId = (request.user as { id: string })?.id;

      if (!userId) {
        return reply.code(401).send({ error: "User not authenticated" });
      }

      const result = await scheduler.ensureScheduleForUser(userId);
      return reply.send(result);
    }
  );

  fastify.get(
    "/:userId",
    async (request, reply) => {
      const params = request.params as { userId: string };
      const authedUser = (request.user as { id: string })?.id;
      if (authedUser !== params.userId) {
        return reply.code(403).send({ error: "Forbidden" });
      }
      const schedule = await scheduler.getSchedule(params.userId);

      if (!schedule) {
        return reply.code(404).send({ error: "Schedule not found" });
      }

      return reply.send(schedule);
    }
  );

  fastify.post(
    "/:userId/pause",
    async (request, reply) => {
      const params = request.params as { userId: string };
      const authedUser = (request.user as { id: string })?.id;
      if (authedUser !== params.userId) {
        return reply.code(403).send({ error: "Forbidden" });
      }
      await scheduler.pauseSchedule(params.userId);
      return reply.send({ paused: true });
    }
  );

  fastify.post(
    "/:userId/resume",
    async (request, reply) => {
      const params = request.params as { userId: string };
      const authedUser = (request.user as { id: string })?.id;
      if (authedUser !== params.userId) {
        return reply.code(403).send({ error: "Forbidden" });
      }
      await scheduler.resumeSchedule(params.userId);
      return reply.send({ resumed: true });
    }
  );

  fastify.get(
    "/",
    async (request, reply) => {
      const limit = parseInt((request.query as { limit?: string }).limit || "100");
      const offset = parseInt((request.query as { offset?: string }).offset || "0");

      const schedules = await scheduler.listActiveSchedules(limit, offset);
      return reply.send(schedules);
    }
  );
}
