import type { Knex } from 'knex';
import { z } from 'zod';
import { db } from '../../db/knex';
import { clearMemoryCache } from '../../middleware/cache';

/** Admin lists can be larger than public ones (tables page client-side). */
export const adminPage = z.object({
  page: z.coerce.number().int().min(1).default(1),
  pageSize: z.coerce.number().int().min(1).max(500).default(50),
  q: z.string().trim().max(120).optional(),
});
export type AdminPage = z.infer<typeof adminPage>;
export const idParam = z.object({ id: z.string().regex(/^\d+$/, 'Invalid id') });

export async function paged<T>(qb: Knex.QueryBuilder, p: AdminPage, map: (r: never) => T) {
  const totalRow = (await qb.clone().clearSelect().clearOrder().count({ n: '*' }).first()) as
    { n: number } | undefined;
  const rows = await qb.offset((p.page - 1) * p.pageSize).limit(p.pageSize);
  return { items: rows.map(map), page: p.page, pageSize: p.pageSize, total: Number(totalRow?.n ?? 0) };
}

/** Writes invalidate the public in-memory cache so the website shows edits at once (CDN/browser cache still up to 5 min). */
export async function write<T>(fn: (trx: Knex.Transaction) => Promise<T>) {
  const out = await db.transaction(fn);
  clearMemoryCache();
  return out;
}

export async function recordRedirect(
  trx: Knex.Transaction,
  entity: string,
  oldSlug: string,
  newSlug: string,
) {
  if (oldSlug === newSlug) return;
  // point older redirects at the newest slug, then add old → new
  await trx('slug_redirects').where({ entity, new_slug: oldSlug }).update({ new_slug: newSlug });
  await trx('slug_redirects').where({ entity, old_slug: newSlug }).del();
  await trx('slug_redirects')
    .insert({ entity, old_slug: oldSlug, new_slug: newSlug })
    .onConflict(['entity', 'old_slug'])
    .merge({ new_slug: newSlug });
}

export const idFor = async (trx: Knex | Knex.Transaction, table: string, slug: string) =>
  (await trx(table).select('id').where({ slug }).first())?.id as string | undefined;

/** "Tablet (Extended Release)" → the dosage form whose match_labels contain it (MySQL + MariaDB). */
export const dosageFormIdForLabel = async (trx: Knex | Knex.Transaction, label: string) =>
  (
    await trx('dosage_forms')
      .select('id')
      .whereRaw('JSON_CONTAINS(match_labels, JSON_QUOTE(?))', [label])
      .first()
  )?.id ?? null;

/** Best-guess icon from a form label (same rules as the admin CSV import). */
export function iconForForm(form: string) {
  const f = form.toLowerCase();
  if (f.includes('capsule')) return 'capsule' as const;
  if (f.includes('suppos')) return 'suppository' as const;
  if (f.includes('suspension')) return 'suspension' as const;
  if (f.includes('syrup')) return 'syrup' as const;
  if (f.includes('drop')) return 'drops' as const;
  if (f.includes('infusion')) return 'iv' as const;
  if (f.includes('inject')) return 'injection' as const;
  if (f.includes('cream') || f.includes('ointment')) return 'cream' as const;
  if (f.includes('powder')) return 'powder' as const;
  return 'tablet' as const;
}
