import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
import {
  getSchedulerStatus,
  JOB_KEYS,
  listSchedulerRuns,
  refreshScheduler,
  runSchedulerJobNow,
} from "../services/scheduler.js"

function parseJobKey(raw: string | undefined): typeof JOB_KEYS[number] | null {
  const s = String(raw ?? "").trim()
  return (JOB_KEYS as readonly string[]).includes(s) ? (s as typeof JOB_KEYS[number]) : null
}

const schedulerRoutes: FastifyPluginAsyncZod = async (app) => {
  app.get("/scheduler/status", async (_req, reply) => {
    return reply.send(getSchedulerStatus())
  })

  app.get("/scheduler/runs", async (req, reply) => {
    const q = req.query as { jobKey?: string; limit?: string; offset?: string }
    const jobKey = q.jobKey ? parseJobKey(q.jobKey) : undefined
    if (q.jobKey && jobKey == null) {
      return reply.status(400).send({ error: "Некорректный jobKey" })
    }
    const limit = Math.min(200, Math.max(1, Number.parseInt(String(q.limit ?? "50"), 10) || 50))
    const offset = Math.max(0, Number.parseInt(String(q.offset ?? "0"), 10) || 0)
    return reply.send(listSchedulerRuns({ jobKey: jobKey ?? undefined, limit, offset }))
  })

  app.post("/scheduler/refresh", async (_req, reply) => {
    refreshScheduler()
    return reply.send({ ok: true, status: getSchedulerStatus() })
  })

  app.post("/scheduler/jobs/:jobKey/run-now", async (req, reply) => {
    const jobKey = parseJobKey(String((req.params as { jobKey?: string }).jobKey ?? ""))
    if (!jobKey) return reply.status(400).send({ error: "Некорректный jobKey" })
    try {
      await runSchedulerJobNow(jobKey)
      return reply.send({ ok: true, status: getSchedulerStatus() })
    } catch (e) {
      const statusCode = (e as Error & { statusCode?: number }).statusCode
      if (statusCode === 409) {
        return reply.status(409).send({ error: "Задача уже выполняется" })
      }
      const msg = e instanceof Error ? e.message : String(e)
      return reply.status(500).send({ error: msg })
    }
  })
}

export default schedulerRoutes
