import { prisma } from "@/lib/prisma";
import { tools as staticTools, getTool as getStaticTool, type Tool, type Tier } from "@/lib/tools";
import { resolveIcon } from "@/lib/iconMap";

export const TOOL_CATEGORIES = ["Convert", "Generate", "Check", "Develop"] as const;
export type ToolCategory = (typeof TOOL_CATEGORIES)[number];

export type DbToolRecord = {
  id: string;
  slug: string;
  name: string;
  shortDesc: string;
  content: string;
  howTo: string | null;
  category: string;
  tier: string;
  price: number;
  icon: string;
  createdAt: Date;
  updatedAt: Date;
};

function toTool(row: DbToolRecord): Tool {
  return {
    slug: row.slug,
    name: row.name,
    shortDesc: row.shortDesc,
    category: (TOOL_CATEGORIES as readonly string[]).includes(row.category)
      ? (row.category as ToolCategory)
      : "Convert",
    icon: resolveIcon(row.icon),
    tier: row.tier === "pro" ? "pro" : "free",
    price: row.price,
    dynamic: true,
  };
}

/** Raw DB rows, admin-panel shape (used by the manage-tools UI). */
export async function listDbTools(): Promise<DbToolRecord[]> {
  return prisma.tool.findMany({ orderBy: { createdAt: "desc" } });
}

/** DB tools mapped into the same shape as the built-in `tools` array. */
export async function getDynamicTools(): Promise<Tool[]> {
  const rows = await prisma.tool.findMany({ orderBy: { createdAt: "desc" } });
  return rows.map(toTool);
}

/** Built-in + admin-added tools, ready to render in listings/dashboards. */
export async function getMergedTools(): Promise<Tool[]> {
  const dynamic = await getDynamicTools();
  return [...staticTools, ...dynamic];
}

/**
 * Look up any tool by slug — checks the built-in list first (so a static
 * page always wins if a slug collides), then falls back to the DB.
 */
export async function getAnyTool(slug: string): Promise<Tool | null> {
  const built = getStaticTool(slug);
  if (built) return built;
  const row = await prisma.tool.findUnique({ where: { slug } });
  return row ? toTool(row) : null;
}

/** Full DB record for the dynamic tool page (needs `content`/`howTo` too). */
export async function getDbToolBySlug(slug: string): Promise<DbToolRecord | null> {
  return prisma.tool.findUnique({ where: { slug } });
}

export function slugify(input: string): string {
  return input
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "");
}

export function isValidCategory(value: string): value is ToolCategory {
  return (TOOL_CATEGORIES as readonly string[]).includes(value);
}

export function isValidTier(value: string): value is Tier {
  return value === "free" || value === "pro";
}
