import { customAlphabet } from "nanoid";
import { prisma } from "../lib/prisma";

// Use a readable alphabet without ambiguous characters (0/O, 1/I/l)
const nanoid = customAlphabet("23456789abcdefghijkmnpqrstuvwxyz", 6);

export async function generateShortLink(fullUrl: string): Promise<string> {
  let shortCode: string = "";
  let exists = true;

  // Keep generating until we find a unique code
  while (exists) {
    shortCode = nanoid();
    const existing = await prisma.shortLink.findUnique({
      where: { shortCode },
    });
    exists = !!existing;
  }

  // Create the short link in the database
  await prisma.shortLink.create({
    data: {
      shortCode,
      fullUrl,
    },
  });

  const domain = process.env.DOMAIN || "localhost:4321";
  return `${domain}/${shortCode}`;
}

export async function resolveShortLink(
  shortCode: string,
): Promise<string | null> {
  const link = await prisma.shortLink.findUnique({
    where: { shortCode },
  });
  return link?.fullUrl || null;
}
