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

export function normalisePath(input: string): string {
  let s = input.trim();
  if (!s) return "";
  if (!s.startsWith("/")) s = "/" + s;
  // Strip trailing slash except for the root path.
  if (s.length > 1 && s.endsWith("/")) s = s.slice(0, -1);
  return s.toLowerCase();
}

export async function findActiveRedirect(source: string): Promise<Redirect | null> {
  const key = normalisePath(source);
  if (!key) return null;
  const [row] = await db
    .select()
    .from(redirects)
    .where(and(eq(redirects.source, key), eq(redirects.active, true)))
    .limit(1);
  return row ?? null;
}

export async function recordRedirectHit(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 counter update failed", err);
  }
}
