import type { FastifyInstance } from "fastify"
import type { RedisKey } from "iovalkey"
import type { ValkeyPluginOptions, ValkeyService } from "./valkeyTypes"
import fastifyPlugin from "fastify-plugin"
import { Redis } from "iovalkey"

export default fastifyPlugin(
  (fastify: FastifyInstance, options: ValkeyPluginOptions, done: any) => {
    const url = options.url || "redis://cache:6379"

    fastify.log.info(`[CACHE] Connecting to ${url}`)

    const client = new Redis(url, {
      retryStrategy: (times) => {
        const delay = Math.min(times * 50, 2000)

        return delay
      },
      ...options.options,
    })

    // Handle connection events
    client.on("error", (error) => {
      fastify.log.error("[CACHE] Error:", error)
    })
    client.on("connect", () => fastify.log.info("[CACHE] Connected"))
    client.on("reconnecting", () => fastify.log.info("[CACHE] Reconnecting..."))

    const valkeyService: ValkeyService = {
      get: async (key: string) => client.get(key),
      set: async (key: string, value: string, expireSeconds?: number) => {
        if (expireSeconds) {
          return client.setex(key, expireSeconds, value)
        }

        return client.set(key, value)
      },
      del: async (...args: [...keys: RedisKey[]]) => client.del(args),
      exists: async (key: string) => client.exists(key),
      incr: async (key: string) => client.incr(key),
      expire: async (key: string, seconds: number) =>
        client.expire(key, seconds),
      multi: () => client.multi() as any,
      setex: async (key: string, seconds: number, value: string) =>
        client.setex(key, seconds, value),
      mget: async (...keys: string[]) => client.mget(keys),
      keys: async (pattern: string) => client.keys(pattern),
      ttl: async (key: string) => client.ttl(key),
    }

    fastify.decorate("cache", valkeyService)

    fastify.addHook("onClose", async () => {
      await client.quit()
    })

    done()
  },
)
