import { db } from "@/lib/db/client";
import { redirects, type Redirect } from "@/lib/db/schema";
import { eq, sql } from "drizzle-orm";

type CacheEntry = {
  map: Map<string, Redirect>;
  at: number;
};

let cache: CacheEntry | null = null;
const TTL_MS = 30_000;

async function refresh(): Promise<CacheEntry> {
  const rows = await db
    .select()
    .from(redirects)
    .where(eq(redirects.active, true));
  const map = new Map<string, Redirect>();
  for (const row of rows) map.set(row.source, row);
  return { map, at: Date.now() };
}

export async function lookupCachedRedirect(
  path: string,
): Promise<Redirect | null> {
  const key = path.toLowerCase();
  if (!cache || Date.now() - cache.at > TTL_MS) {
    try {
      cache = await refresh();
    } catch (err) {
      console.error("[redirects] cache refresh failed", err);
      if (!cache) return null;
    }
  }
  return cache.map.get(key) ?? null;
}

export function invalidateRedirectCache(): void {
  cache = null;
}

export async function bumpRedirectHit(id: string): Promise<void> {
  try {
    await db
      .update(redirects)
      .set({ hits: sql`${redirects.hits} + 1`, lastHitAt: new Date() })
      .where(eq(redirects.id, id));
  } catch (err) {
    console.error("[redirects] hit bump failed", err);
  }
}
