import { Router } from 'express';
import type { Knex } from 'knex';
import { z } from 'zod';
import { db } from '../../db/knex';
import { SECTION_FROM_DB, SECTION_TO_DB, INFO_KEYS } from '../../db/sections';
import { conflict, forbidden, notFound, validationError } from '../../lib/http-errors';
import {
  companySchema,
  conditionSchema,
  dosageFormSchema,
  drugClassSchema,
  genericSchema,
  productSchema,
} from '../../shared/schemas';
import { requireRole } from '../../middleware/auth';
import { validate } from '../../middleware/validate';
import { audit, diffOf } from './audit';
import { quickSummary, review as toReview } from '../public/service';
import { adminPage, dosageFormIdForLabel, idFor, idParam, paged, recordRedirect, write } from './helpers';

const editors = requireRole('admin', 'editor');
const date = (v: unknown) => (v ? String(v).slice(0, 10) : undefined);
const slugTaken = async (trx: Knex | Knex.Transaction, table: string, slug: string, exceptId?: string) =>
  !!(await trx(table)
    .select('id')
    .where({ slug })
    .modify((q) => exceptId && q.whereNot('id', exceptId))
    .first());
const parseJson = (v: unknown) => (typeof v === 'string' ? JSON.parse(v) : v);
/** Reviewer columns joined onto a generic query (SEO Phase 7). */
const withReviewer = (qb: Knex.QueryBuilder) =>
  qb
    .leftJoin('reviewers as rv', 'rv.id', 'g.reviewer_id')
    .select(
      'rv.slug as reviewer_slug',
      'rv.name as reviewer_display',
      'rv.qualification as reviewer_qualification',
    );

/** reviewerSlug → { id, name }; a field error if it doesn't exist. */
async function reviewerFor(trx: Knex | Knex.Transaction, slug: string) {
  const r = await trx('reviewers').select('id', 'name').where({ slug }).first();
  if (!r) throw validationError({ reviewerSlug: ['Choose a reviewer from the list'] });
  return r as { id: string; name: string };
}

/* =============================== GENERICS =============================== */
async function loadGeneric(id: string) {
  const g = await withReviewer(
    db('generics as g')
      .leftJoin('drug_classes as dc', 'dc.id', 'g.drug_class_id')
      .select('g.*', 'dc.slug as class_slug'),
  )
    .where('g.id', id)
    .first();
  if (!g) throw notFound('Generic not found.');
  const info = await db('generic_info').select('section', 'body_en', 'body_bn').where('generic_id', id);
  const conditions = (
    await db('generic_conditions as gc')
      .join('conditions as c', 'c.id', 'gc.condition_id')
      .select('c.slug')
      .where('gc.generic_id', id)
  ).map((r: { slug: string }) => r.slug);
  const combinations = (
    await db('generic_components as gc')
      .join('generics as x', 'x.id', 'gc.combination_generic_id')
      .select('x.slug')
      .where('gc.component_generic_id', id)
  ).map((r: { slug: string }) => r.slug);
  const byKey = Object.fromEntries(
    info.map((r: { section: string; body_en: string; body_bn: string | null }) => [
      SECTION_FROM_DB[r.section],
      { en: r.body_en, ...(r.body_bn ? { bn: r.body_bn } : {}) },
    ]),
  );
  return {
    id: String(g.id),
    slug: g.slug,
    name: g.name,
    catalogue: g.catalogue,
    classSlug: g.class_slug ?? '',
    ...(g.class_label ? { classLabel: g.class_label } : {}),
    ...(g.class_label_bn ? { classLabelBn: g.class_label_bn } : {}),
    ...(g.tagline ? { tagline: g.tagline } : {}),
    ...(g.structure_image_url ? { structureImageUrl: g.structure_image_url } : {}),
    ...(g.chemical_info ? { chemicalInfo: parseJson(g.chemical_info) } : {}),
    ...(g.faq ? { faq: parseJson(g.faq) } : {}),
    conditionSlugs: conditions,
    combinations,
    info: Object.fromEntries(INFO_KEYS.map((k) => [k, byKey[k] ?? { en: '' }])),
    review: toReview(g),
    summary: quickSummary(g),
    sources: parseJson(g.sources) ?? [],
    status: g.status,
    updatedAt: date(g.updated_at),
  };
}

type GenericBody = z.output<typeof genericSchema>;

async function saveGeneric(
  trx: Knex.Transaction,
  v: GenericBody,
  admin: { id: string; role: string; name: string },
  existingId?: string,
) {
  const classId = v.classSlug ? await idFor(trx, 'drug_classes', v.classSlug) : null;
  const errs: Record<string, string[]> = {};
  if (v.classSlug && !classId) errs.classSlug = ['Unknown drug class'];
  if (await slugTaken(trx, 'generics', v.slug, existingId))
    errs.slug = ['Another generic already uses this slug.'];
  if (Object.keys(errs).length) throw validationError(errs);

  const before = existingId ? await trx('generics').where({ id: existingId }).first() : undefined;
  const oldInfo = existingId ? await trx('generic_info').where({ generic_id: existingId }) : [];
  const infoChanged = INFO_KEYS.some((k) => {
    const o = oldInfo.find((r: { section: string }) => r.section === SECTION_TO_DB[k]);
    return (o?.body_en ?? '') !== v.info[k].en || (o?.body_bn ?? '') !== v.info[k].bn;
  });
  // Editors cannot approve; an editor's change to approved text sends it back for pharmacist review.
  let approved = v.reviewStatus === 'approved';
  if (admin.role === 'editor' && approved && (!before || before.review_status !== 'approved' || infoChanged))
    approved = false;
  const reviewer = approved && v.reviewerSlug ? await reviewerFor(trx, v.reviewerSlug) : null;

  const row = {
    slug: v.slug,
    name: v.name,
    catalogue: v.catalogue,
    drug_class_id: classId ?? null,
    class_label: v.classLabel || null,
    class_label_bn: v.classLabelBn || null,
    tagline: v.tagline || null,
    structure_image_url: v.structureImageUrl || null,
    chemical_info: v.chemicalInfo ? JSON.stringify(v.chemicalInfo) : null,
    faq: v.faq && v.faq.length ? JSON.stringify(v.faq) : null,
    sources: JSON.stringify(v.sources),
    review_status: approved ? 'approved' : 'pending',
    reviewer_id: reviewer?.id ?? null,
    reviewer_name: reviewer?.name ?? null,
    reviewed_at: approved ? v.reviewDate || null : null,
    summary_use_en: v.summaryUse.en || null,
    summary_use_bn: v.summaryUse.bn || null,
    summary_dose_en: v.summaryDose.en || null,
    summary_dose_bn: v.summaryDose.bn || null,
    summary_how_to_take_en: v.summaryHowToTake?.en || null,
    summary_how_to_take_bn: v.summaryHowToTake?.bn || null,
    summary_safety_en: v.summarySafety?.en || null,
    summary_safety_bn: v.summarySafety?.bn || null,
    food_timing: v.foodTiming || null,
    prescription: v.prescription || null,
  };
  let id = existingId;
  if (existingId) {
    await trx('generics').where({ id: existingId }).update(row);
    if (before.slug !== v.slug) await recordRedirect(trx, 'generic', before.slug, v.slug);
  } else [id] = await trx('generics').insert({ ...row, status: 'published' });

  await trx('generic_info').where({ generic_id: id }).del();
  const info = INFO_KEYS.filter((k) => v.info[k].en || v.info[k].bn).map((k) => ({
    generic_id: id,
    section: SECTION_TO_DB[k],
    body_en: v.info[k].en,
    body_bn: v.info[k].bn || null,
  }));
  if (info.length) await trx('generic_info').insert(info);

  await trx('generic_conditions').where({ generic_id: id }).del();
  const condIds = v.conditionSlugs.length
    ? await trx('conditions').select('id').whereIn('slug', v.conditionSlugs)
    : [];
  if (condIds.length)
    await trx('generic_conditions').insert(
      condIds.map((c: { id: string }) => ({ generic_id: id, condition_id: c.id })),
    );

  await trx('generic_components').where({ component_generic_id: id }).del();
  const comboIds = v.combinations.length
    ? await trx('generics').select('id').whereIn('slug', v.combinations).whereNot('id', id!)
    : [];
  if (comboIds.length)
    await trx('generic_components').insert(
      comboIds.map((c: { id: string }) => ({ combination_generic_id: c.id, component_generic_id: id })),
    );

  await audit(
    {
      adminId: admin.id,
      action: existingId ? 'updated' : 'created',
      entity: 'generic',
      entityId: id,
      label: v.name,
      diff: { ...diffOf(before, row), ...(infoChanged ? { info: 'changed' } : {}) },
    },
    trx,
  );
  if (approved && before?.review_status !== 'approved')
    await audit(
      { adminId: admin.id, action: 'approved', entity: 'generic', entityId: id, label: v.name },
      trx,
    );
  return String(id);
}

/* ============================== ROUTER ============================== */
export function contentRouter() {
  const r = Router();

  /* ---------- generics ---------- */
  const genericList = adminPage.extend({ reviewStatus: z.enum(['approved', 'pending']).optional() });
  r.get('/generics', validate({ query: genericList }), async (_req, res) => {
    const q = res.locals.valid!.query as z.infer<typeof genericList>;
    const qb = withReviewer(db('generics as g'))
      .leftJoin('drug_classes as dc', 'dc.id', 'g.drug_class_id')
      .select(
        'g.id',
        'g.slug',
        'g.name',
        'g.catalogue',
        'g.class_label',
        'g.structure_image_url',
        'g.review_status',
        'g.reviewer_name',
        'g.reviewed_at',
        'g.updated_at',
        'dc.slug as class_slug',
        'dc.name as class_name',
      )
      .select(db.raw('(select count(*) from brands b where b.generic_id = g.id) as brand_count'))
      .select(
        db.raw(
          "(select count(*) from generic_info gi where gi.generic_id = g.id and gi.body_en <> '') as sections_written",
        ),
      )
      .select(
        db.raw(
          '(select group_concat(c.slug) from generic_conditions gc join conditions c on c.id = gc.condition_id where gc.generic_id = g.id) as condition_slugs',
        ),
      )
      .select(
        db.raw(
          "(select count(*) from generic_info gi where gi.generic_id = g.id and gi.section = 'indications' and gi.body_en <> '') as has_indications",
        ),
      )
      .orderBy('g.name');
    if (q.q) qb.where('g.name', 'like', `%${q.q}%`);
    if (q.reviewStatus) qb.where('g.review_status', q.reviewStatus);
    res.json(
      await paged(qb, q, (g: Record<string, never>) => ({
        id: String(g.id),
        slug: g.slug,
        name: g.name,
        catalogue: g.catalogue,
        classSlug: g.class_slug ?? '',
        className: g.class_name ?? '',
        ...(g.class_label ? { classLabel: g.class_label } : {}),
        ...(g.structure_image_url ? { structureImageUrl: g.structure_image_url } : {}),
        brandCount: Number(g.brand_count),
        completeness: Math.round((Number(g.sections_written) / INFO_KEYS.length) * 100),
        conditionSlugs: String(g.condition_slugs ?? '')
          .split(',')
          .filter(Boolean),
        hasIndications: Number(g.has_indications) > 0,
        review: toReview(g as never),
        updatedAt: date(g.updated_at),
      })),
    );
  });
  r.get('/generics/:id', validate({ params: idParam }), async (_req, res) =>
    res.json(await loadGeneric(res.locals.valid!.params.id as string)),
  );
  r.post('/generics', editors, validate({ body: genericSchema }), async (_req, res) => {
    const id = await write((trx) =>
      saveGeneric(trx, res.locals.valid!.body as GenericBody, res.locals.admin!),
    );
    res.status(201).json(await loadGeneric(id));
  });
  // pharmacists may edit clinical text (and approve); editors may edit but not approve
  r.put('/generics/:id', validate({ params: idParam, body: genericSchema }), async (_req, res) => {
    const id = res.locals.valid!.params.id as string;
    if (!(await db('generics').where({ id }).first())) throw notFound('Generic not found.');
    await write((trx) => saveGeneric(trx, res.locals.valid!.body as GenericBody, res.locals.admin!, id));
    res.json(await loadGeneric(id));
  });
  r.post(
    '/generics/:id/approve',
    requireRole('admin', 'pharmacist'),
    validate({
      params: idParam,
      body: z.object({
        reviewerSlug: z.string().trim().min(1, 'Choose the reviewing pharmacist').max(160),
        date: z
          .string()
          .regex(/^\d{4}-\d{2}-\d{2}$/)
          .optional(),
      }),
    }),
    async (_req, res) => {
      const id = res.locals.valid!.params.id as string;
      const b = res.locals.valid!.body as { reviewerSlug: string; date?: string };
      const g = await db('generics').where({ id }).first();
      if (!g) throw notFound('Generic not found.');
      const ind = await db('generic_info').where({ generic_id: id, section: 'indications' }).first();
      if (!ind?.body_en)
        throw validationError({ 'info.indications.en': ['Indications are required before approval'] });
      const reviewer = await reviewerFor(db, b.reviewerSlug);
      await write(async (trx) => {
        await trx('generics')
          .where({ id })
          .update({
            review_status: 'approved',
            reviewer_id: reviewer.id,
            reviewer_name: reviewer.name,
            reviewed_at: b.date ?? new Date().toISOString().slice(0, 10),
          });
        await audit(
          {
            adminId: res.locals.admin!.id,
            action: 'approved',
            entity: 'generic',
            entityId: id,
            label: g.name,
          },
          trx,
        );
      });
      res.json(await loadGeneric(id));
    },
  );
  r.delete('/generics/:id', editors, validate({ params: idParam }), async (_req, res) => {
    const id = res.locals.valid!.params.id as string;
    const g = await db('generics').where({ id }).first();
    if (!g) throw notFound('Generic not found.');
    const [{ n }] = await db('brands').count({ n: '*' }).where({ generic_id: id });
    if (Number(n))
      throw conflict(`${n} brand(s) use ${g.name}. Move or delete them first, or archive the generic.`, {
        brands: Number(n),
      });
    await write(async (trx) => {
      await trx('generics').where({ id }).del();
      await audit(
        { adminId: res.locals.admin!.id, action: 'deleted', entity: 'generic', entityId: id, label: g.name },
        trx,
      );
    });
    res.status(204).end();
  });

  /* ---------- companies ---------- */
  const toCompany = (c: Record<string, never>) => ({
    id: String(c.id),
    slug: c.slug,
    name: c.name,
    catalogue: String(c.catalogues).split(',').filter(Boolean),
    status: c.status,
    brandCount: Number(c.brand_count ?? 0),
  });
  const companyQ = () =>
    db('companies as c')
      .select('c.*')
      .select(db.raw('(select count(*) from brands b where b.company_id = c.id) as brand_count'));
  r.get('/companies', validate({ query: adminPage }), async (_req, res) => {
    const q = res.locals.valid!.query as z.infer<typeof adminPage>;
    const qb = companyQ().orderBy('c.name');
    if (q.q) qb.where('c.name', 'like', `%${q.q}%`);
    res.json(await paged(qb, q, toCompany));
  });
  const saveCompany = async (v: z.infer<typeof companySchema>, adminId: string, id?: string) =>
    write(async (trx) => {
      if (await slugTaken(trx, 'companies', v.slug, id))
        throw validationError({ slug: ['This slug is already used.'] });
      const before = id ? await trx('companies').where({ id }).first() : undefined;
      const row = { slug: v.slug, name: v.name, catalogues: v.catalogue.join(',') };
      if (id) {
        await trx('companies').where({ id }).update(row);
        if (before.slug !== v.slug) await recordRedirect(trx, 'company', before.slug, v.slug);
      } else [id] = await trx('companies').insert({ ...row, status: 'published' });
      await audit(
        {
          adminId,
          action: before ? 'updated' : 'created',
          entity: 'company',
          entityId: id,
          label: v.name,
          diff: diffOf(before, row),
        },
        trx,
      );
      return String(id);
    });
  r.post('/companies', editors, validate({ body: companySchema }), async (_req, res) => {
    const id = await saveCompany(
      res.locals.valid!.body as z.infer<typeof companySchema>,
      res.locals.admin!.id,
    );
    res.status(201).json(toCompany(await companyQ().where('c.id', id).first()));
  });
  r.put('/companies/:id', editors, validate({ params: idParam, body: companySchema }), async (_req, res) => {
    const id = res.locals.valid!.params.id as string;
    if (!(await db('companies').where({ id }).first())) throw notFound('Company not found.');
    await saveCompany(res.locals.valid!.body as z.infer<typeof companySchema>, res.locals.admin!.id, id);
    res.json(toCompany(await companyQ().where('c.id', id).first()));
  });
  r.delete('/companies/:id', editors, validate({ params: idParam }), async (_req, res) => {
    const id = res.locals.valid!.params.id as string;
    const c = await companyQ().where('c.id', id).first();
    if (!c) throw notFound('Company not found.');
    if (Number(c.brand_count))
      throw conflict(
        `${c.name} has ${c.brand_count} brand(s). Move them to another company first, or archive it.`,
        { brands: Number(c.brand_count) },
      );
    await write(async (trx) => {
      await trx('companies').where({ id }).del();
      await audit(
        { adminId: res.locals.admin!.id, action: 'deleted', entity: 'company', entityId: id, label: c.name },
        trx,
      );
    });
    res.status(204).end();
  });

  /* ---------- drug classes + groups ---------- */
  r.get('/drug-class-groups', async (_req, res) =>
    res.json({
      items: await db('drug_class_groups')
        .select('id', 'slug', 'name', 'name_bn as nameBn', 'sort_order as sortOrder')
        .orderBy('sort_order'),
    }),
  );
  const classQ = () =>
    db('drug_classes as dc')
      .join('drug_class_groups as g', 'g.id', 'dc.group_id')
      .select(
        'dc.id',
        'dc.slug',
        'dc.name',
        'dc.name_bn',
        'dc.description',
        'dc.description_bn',
        'g.slug as group_slug',
        'g.name as group_name',
      )
      .select(db.raw('(select count(*) from generics x where x.drug_class_id = dc.id) as generic_count'));
  const toClass = (c: Record<string, never>) => ({
    id: String(c.id),
    slug: c.slug,
    name: c.name,
    ...(c.name_bn ? { nameBn: c.name_bn } : {}),
    description: c.description,
    ...(c.description_bn ? { descriptionBn: c.description_bn } : {}),
    groupSlug: c.group_slug,
    groupName: c.group_name,
    genericCount: Number(c.generic_count),
  });
  r.get('/drug-classes', validate({ query: adminPage }), async (_req, res) => {
    const q = res.locals.valid!.query as z.infer<typeof adminPage>;
    const qb = classQ().orderBy('g.sort_order').orderBy('dc.sort_order');
    if (q.q) qb.where((w) => w.where('dc.name', 'like', `%${q.q}%`).orWhere('g.name', 'like', `%${q.q}%`));
    res.json(await paged(qb, q, toClass));
  });
  const saveClass = async (v: z.infer<typeof drugClassSchema>, adminId: string, id?: string) =>
    write(async (trx) => {
      const groupId = await idFor(trx, 'drug_class_groups', v.groupSlug);
      if (!groupId) throw validationError({ groupSlug: ['Unknown group'] });
      if (await slugTaken(trx, 'drug_classes', v.slug, id))
        throw validationError({ slug: ['This slug is already used.'] });
      const before = id ? await trx('drug_classes').where({ id }).first() : undefined;
      const row = {
        slug: v.slug,
        name: v.name,
        name_bn: v.nameBn || null,
        group_id: groupId,
        description: v.description,
        description_bn: v.descriptionBn || null,
      };
      if (id) {
        await trx('drug_classes').where({ id }).update(row);
        if (before.slug !== v.slug) await recordRedirect(trx, 'drug_class', before.slug, v.slug);
      } else [id] = await trx('drug_classes').insert({ ...row, status: 'published' });
      await audit(
        {
          adminId,
          action: before ? 'updated' : 'created',
          entity: 'drug_class',
          entityId: id,
          label: v.name,
          diff: diffOf(before, row),
        },
        trx,
      );
      return String(id);
    });
  r.post('/drug-classes', editors, validate({ body: drugClassSchema }), async (_req, res) => {
    const id = await saveClass(
      res.locals.valid!.body as z.infer<typeof drugClassSchema>,
      res.locals.admin!.id,
    );
    res.status(201).json(toClass(await classQ().where('dc.id', id).first()));
  });
  r.put(
    '/drug-classes/:id',
    editors,
    validate({ params: idParam, body: drugClassSchema }),
    async (_req, res) => {
      const id = res.locals.valid!.params.id as string;
      if (!(await db('drug_classes').where({ id }).first())) throw notFound('Drug class not found.');
      await saveClass(res.locals.valid!.body as z.infer<typeof drugClassSchema>, res.locals.admin!.id, id);
      res.json(toClass(await classQ().where('dc.id', id).first()));
    },
  );
  r.delete('/drug-classes/:id', editors, validate({ params: idParam }), async (_req, res) => {
    const id = res.locals.valid!.params.id as string;
    const c = await classQ().where('dc.id', id).first();
    if (!c) throw notFound('Drug class not found.');
    if (Number(c.generic_count))
      throw conflict(`${c.generic_count} generic(s) use ${c.name}. Move them first.`, {
        generics: Number(c.generic_count),
      });
    await write(async (trx) => {
      await trx('drug_classes').where({ id }).del();
      await audit(
        {
          adminId: res.locals.admin!.id,
          action: 'deleted',
          entity: 'drug_class',
          entityId: id,
          label: c.name,
        },
        trx,
      );
    });
    res.status(204).end();
  });

  /* ---------- dosage forms ---------- */
  const toForm = (f: Record<string, never>) => ({
    id: String(f.id),
    slug: f.slug,
    name: f.name,
    ...(f.name_bn ? { nameBn: f.name_bn } : {}),
    icon: f.icon,
    ...(f.route ? { route: f.route } : {}),
    ...(f.route_bn ? { routeBn: f.route_bn } : {}),
    description: f.description,
    ...(f.description_bn ? { descriptionBn: f.description_bn } : {}),
    match: parseJson(f.match_labels) ?? [],
    ...(f.generic_count !== undefined ? { genericCount: Number(f.generic_count) } : {}),
    ...(f.brand_count !== undefined ? { brandCount: Number(f.brand_count) } : {}),
  });
  r.get('/dosage-forms', async (_req, res) =>
    res.json({
      items: (
        await db('dosage_forms as df')
          .select('df.*')
          .select(
            db.raw('(select count(*) from generic_dosage_forms gdf where gdf.dosage_form_id = df.id) as generic_count'),
          )
          .select(db.raw('(select count(*) from brands b where b.dosage_form_id = df.id) as brand_count'))
          .orderBy('df.sort_order')
      ).map(toForm),
    }),
  );
  const saveForm = async (v: z.infer<typeof dosageFormSchema>, adminId: string, id?: string) =>
    write(async (trx) => {
      if (await slugTaken(trx, 'dosage_forms', v.slug, id))
        throw validationError({ slug: ['This slug is already used.'] });
      const match = v.match
        .split(',')
        .map((x) => x.trim())
        .filter(Boolean);
      const before = id ? await trx('dosage_forms').where({ id }).first() : undefined;
      const row = {
        slug: v.slug,
        name: v.name,
        name_bn: v.nameBn || null,
        icon: v.icon,
        route: v.route || null,
        route_bn: v.routeBn || null,
        description: v.description,
        description_bn: v.descriptionBn || null,
        match_labels: JSON.stringify(match),
      };
      if (id) {
        await trx('dosage_forms').where({ id }).update(row);
        if (before.slug !== v.slug) await recordRedirect(trx, 'dosage_form', before.slug, v.slug);
      } else [id] = await trx('dosage_forms').insert(row);
      // re-link brands whose form label now matches this form
      for (const label of match)
        await trx('brands')
          .where({ form_label: label })
          .update({ dosage_form_id: await dosageFormIdForLabel(trx, label) });
      await audit(
        {
          adminId,
          action: before ? 'updated' : 'created',
          entity: 'dosage_form',
          entityId: id,
          label: v.name,
          diff: diffOf(before, row),
        },
        trx,
      );
      return String(id);
    });
  r.post('/dosage-forms', editors, validate({ body: dosageFormSchema }), async (_req, res) => {
    const id = await saveForm(
      res.locals.valid!.body as z.infer<typeof dosageFormSchema>,
      res.locals.admin!.id,
    );
    res.status(201).json(toForm(await db('dosage_forms').where({ id }).first()));
  });
  r.put(
    '/dosage-forms/:id',
    editors,
    validate({ params: idParam, body: dosageFormSchema }),
    async (_req, res) => {
      const id = res.locals.valid!.params.id as string;
      if (!(await db('dosage_forms').where({ id }).first())) throw notFound('Dosage form not found.');
      await saveForm(res.locals.valid!.body as z.infer<typeof dosageFormSchema>, res.locals.admin!.id, id);
      res.json(toForm(await db('dosage_forms').where({ id }).first()));
    },
  );
  r.delete('/dosage-forms/:id', editors, validate({ params: idParam }), async (_req, res) => {
    const id = res.locals.valid!.params.id as string;
    const f = await db('dosage_forms').where({ id }).first();
    if (!f) throw notFound('Dosage form not found.');
    // brands keep their form label; the FK is ON DELETE SET NULL
    await write(async (trx) => {
      await trx('dosage_forms').where({ id }).del();
      await audit(
        {
          adminId: res.locals.admin!.id,
          action: 'deleted',
          entity: 'dosage_form',
          entityId: id,
          label: f.name,
        },
        trx,
      );
    });
    res.status(204).end();
  });

  /* ---------- conditions ---------- */
  const loadCondition = async (id: string) => {
    const c = await db('conditions as cd')
      .select('cd.*')
      .select(
        db.raw('(select count(*) from generic_conditions gc where gc.condition_id = cd.id) as generic_count'),
      )
      .where('cd.id', id)
      .first();
    if (!c) throw notFound('Condition not found.');
    const rel = await db('condition_related as cr')
      .join('conditions as x', 'x.id', 'cr.related_condition_id')
      .select('x.slug')
      .where('cr.condition_id', id);
    return {
      id: String(c.id),
      slug: c.slug,
      name: c.name,
      guidance: c.guidance ?? '',
      relatedSlugs: rel.map((x: { slug: string }) => x.slug),
      genericCount: Number(c.generic_count),
    };
  };
  r.get('/conditions', validate({ query: adminPage }), async (_req, res) => {
    const q = res.locals.valid!.query as z.infer<typeof adminPage>;
    const qb = db('conditions').select('id').orderBy('name');
    if (q.q) qb.where('name', 'like', `%${q.q}%`);
    const page = await paged(qb, q, (row: { id: string }) => row.id);
    res.json({
      ...page,
      items: await Promise.all(page.items.map((id: string) => loadCondition(String(id)))),
    });
  });
  const saveCondition = async (
    v: z.infer<typeof conditionSchema>,
    admin: { id: string; role: string },
    id?: string,
  ) =>
    write(async (trx) => {
      if (await slugTaken(trx, 'conditions', v.slug, id))
        throw validationError({ slug: ['This slug is already used.'] });
      const before = id ? await trx('conditions').where({ id }).first() : undefined;
      // guidance must be written or reviewed by a pharmacist (SEO.md §9)
      if (admin.role === 'editor' && (before?.guidance ?? '') !== v.guidance)
        throw forbidden('Only a pharmacist or admin can edit guidance.');
      const row = { slug: v.slug, name: v.name, guidance: v.guidance || null };
      if (id) {
        await trx('conditions').where({ id }).update(row);
        if (before.slug !== v.slug) await recordRedirect(trx, 'condition', before.slug, v.slug);
      } else [id] = await trx('conditions').insert({ ...row, status: 'published' });
      await trx('condition_related').where({ condition_id: id }).del();
      const rel = v.relatedSlugs.length
        ? await trx('conditions').select('id').whereIn('slug', v.relatedSlugs).whereNot('id', id!)
        : [];
      if (rel.length)
        await trx('condition_related').insert(
          rel.map((x: { id: string }) => ({ condition_id: id, related_condition_id: x.id })),
        );
      await audit(
        {
          adminId: admin.id,
          action: before ? 'updated' : 'created',
          entity: 'condition',
          entityId: id,
          label: v.name,
          diff: diffOf(before, row),
        },
        trx,
      );
      return String(id);
    });
  r.post('/conditions', editors, validate({ body: conditionSchema }), async (_req, res) => {
    const id = await saveCondition(
      res.locals.valid!.body as z.infer<typeof conditionSchema>,
      res.locals.admin!,
    );
    res.status(201).json(await loadCondition(id));
  });
  r.put('/conditions/:id', validate({ params: idParam, body: conditionSchema }), async (_req, res) => {
    const id = res.locals.valid!.params.id as string;
    if (!(await db('conditions').where({ id }).first())) throw notFound('Condition not found.');
    await saveCondition(res.locals.valid!.body as z.infer<typeof conditionSchema>, res.locals.admin!, id);
    res.json(await loadCondition(id));
  });
  r.delete('/conditions/:id', editors, validate({ params: idParam }), async (_req, res) => {
    const id = res.locals.valid!.params.id as string;
    const c = await db('conditions').where({ id }).first();
    if (!c) throw notFound('Condition not found.');
    await write(async (trx) => {
      await trx('conditions').where({ id }).del(); // generic links cascade
      await audit(
        {
          adminId: res.locals.admin!.id,
          action: 'deleted',
          entity: 'condition',
          entityId: id,
          label: c.name,
        },
        trx,
      );
    });
    res.status(204).end();
  });

  /* ---------- vet/agro products (stored as brands + tags, Q3) ---------- */
  const loadProduct = async (slug: string) => {
    const b = await db('brands as b')
      .join('companies as c', 'c.id', 'b.company_id')
      .select('b.*', 'c.slug as company_slug')
      .where('b.slug', slug)
      .whereIn('b.catalogue', ['vet', 'agro'])
      .first();
    if (!b) throw notFound('Product not found.');
    const tags = await db('brand_tags as bt')
      .join('catalogue_tags as t', 't.id', 'bt.tag_id')
      .select('t.slug', 't.name', 't.kind')
      .where('bt.brand_id', b.id);
    return {
      slug: b.slug,
      name: b.name,
      catalogue: b.catalogue,
      type: tags.find((t: { kind: string }) => t.kind === 'product_type')?.name ?? '',
      animalsOrCrops: tags
        .filter((t: { kind: string }) => t.kind !== 'product_type')
        .map((t: { slug: string }) => t.slug),
      form: b.form_label,
      formIcon: b.form_icon,
      strength: b.strength,
      genericName: b.ingredient_label ?? '',
      companySlug: b.company_slug,
      withdrawalPeriod: b.withdrawal_period ?? '',
      targetPest: b.target_pest ?? '',
      doseRate: b.dose_rate ?? '',
    };
  };
  r.get(
    '/catalogue-products',
    validate({ query: z.object({ catalogue: z.enum(['vet', 'agro']).optional() }) }),
    async (_req, res) => {
      const { catalogue } = res.locals.valid!.query as { catalogue?: 'vet' | 'agro' };
      const rows = await db('brands')
        .select('slug')
        .whereIn('catalogue', catalogue ? [catalogue] : ['vet', 'agro'])
        .orderBy('name');
      res.json({ items: await Promise.all(rows.map((r: { slug: string }) => loadProduct(r.slug))) });
    },
  );
  r.get(
    '/catalogue-tags',
    validate({
      query: z.object({
        catalogue: z.enum(['vet', 'agro']).optional(),
        kind: z.enum(['animal', 'crop', 'product_type']).optional(),
      }),
    }),
    async (_req, res) => {
      const q = res.locals.valid!.query as { catalogue?: string; kind?: string };
      res.json({
        items: await db('catalogue_tags')
          .select('id', 'slug', 'name', 'kind', 'catalogue')
          .modify((b) => {
            if (q.catalogue) b.where('catalogue', q.catalogue);
            if (q.kind) b.where('kind', q.kind);
          })
          .orderBy('sort_order'),
      });
    },
  );
  const saveProduct = async (v: z.infer<typeof productSchema>, adminId: string, oldSlug?: string) =>
    write(async (trx) => {
      const companyId = await idFor(trx, 'companies', v.companySlug);
      if (!companyId) throw validationError({ companySlug: ['Unknown company'] });
      const existing = oldSlug ? await trx('brands').where({ slug: oldSlug }).first() : undefined;
      if (await slugTaken(trx, 'brands', v.slug, existing?.id))
        throw validationError({ slug: ['This slug is already used.'] });
      const row = {
        slug: v.slug,
        name: v.name,
        catalogue: v.catalogue,
        generic_id: null,
        ingredient_label: v.genericName,
        company_id: companyId,
        dosage_form_id: await dosageFormIdForLabel(trx, v.form),
        form_label: v.form,
        form_icon: v.formIcon,
        strength: v.strength,
        withdrawal_period: v.withdrawalPeriod || null,
        target_pest: v.targetPest || null,
        dose_rate: v.doseRate || null,
      };
      let id = existing?.id;
      if (existing) {
        await trx('brands').where({ id }).update(row);
        if (existing.slug !== v.slug) await recordRedirect(trx, 'product', existing.slug, v.slug);
      } else
        [id] = await trx('brands').insert({
          ...row,
          status: 'published',
          added_at: new Date().toISOString().slice(0, 10),
        });
      const kind = v.catalogue === 'vet' ? 'animal' : 'crop';
      const tagRows = await trx('catalogue_tags')
        .select('id', 'slug', 'name', 'kind')
        .where('catalogue', v.catalogue)
        .where((w) =>
          w
            .where((x) => x.where('kind', kind).whereIn('slug', v.animalsOrCrops))
            .orWhere((x) => x.where('kind', 'product_type').where('name', v.type)),
        );
      if (!tagRows.some((t: { kind: string }) => t.kind === 'product_type'))
        throw validationError({ type: ['Unknown type'] });
      await trx('brand_tags').where({ brand_id: id }).del();
      await trx('brand_tags').insert(tagRows.map((t: { id: string }) => ({ brand_id: id, tag_id: t.id })));
      await audit(
        { adminId, action: existing ? 'updated' : 'created', entity: 'product', entityId: id, label: v.name },
        trx,
      );
      return v.slug;
    });
  const slugParam = z.object({ slug: z.string().regex(/^[a-z0-9-]+$/) });
  r.post('/catalogue-products', editors, validate({ body: productSchema }), async (_req, res) => {
    const slug = await saveProduct(
      res.locals.valid!.body as z.infer<typeof productSchema>,
      res.locals.admin!.id,
    );
    res.status(201).json(await loadProduct(slug));
  });
  r.put(
    '/catalogue-products/:slug',
    editors,
    validate({ params: slugParam, body: productSchema }),
    async (_req, res) => {
      const slug = await saveProduct(
        res.locals.valid!.body as z.infer<typeof productSchema>,
        res.locals.admin!.id,
        res.locals.valid!.params.slug as string,
      );
      res.json(await loadProduct(slug));
    },
  );
  r.delete('/catalogue-products/:slug', editors, validate({ params: slugParam }), async (_req, res) => {
    const slug = res.locals.valid!.params.slug as string;
    const b = await db('brands').where({ slug }).whereIn('catalogue', ['vet', 'agro']).first();
    if (!b) throw notFound('Product not found.');
    await write(async (trx) => {
      await trx('brands').where({ id: b.id }).del();
      await audit(
        {
          adminId: res.locals.admin!.id,
          action: 'deleted',
          entity: 'product',
          entityId: b.id,
          label: b.name,
        },
        trx,
      );
    });
    res.status(204).end();
  });

  return r;
}
