import type { Knex } from 'knex';
import { brandSlug, slugify } from '../../shared/slug';

/**
 * SEO Phase 2: every row has a clean, unique slug.
 * - Empty or invalid slugs (capitals, spaces, symbols) get one from the name (brands: name + strength + form),
 *   with -2, -3… only when needed.
 * - Valid slugs are left alone: a published address never changes silently.
 * - A fixed old slug is stored in slug_redirects, so its old address answers 301.
 * - Every change is written to slug_backfill_log so `down` can put it back exactly.
 */
const VALID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;

type Row = Record<string, string>;
type Table = {
  table: string;
  /** slug_redirects.entity for a row (null: no public page of its own) */
  entity: (r: Row) => string | null;
  source: (r: Row) => string;
  /** slugs only need to be unique inside this group (catalogue tags) */
  scope?: (r: Row) => string;
};

const TABLES: Table[] = [
  {
    table: 'brands',
    // vet/agro products live in `brands` too, with their own redirect type
    entity: (r) => (r.catalogue === 'human' ? 'brand' : 'product'),
    source: (r) => brandSlug(r.name, r.strength ?? '', r.form_label ?? ''),
  },
  { table: 'generics', entity: () => 'generic', source: (r) => slugify(r.name) },
  { table: 'companies', entity: () => 'company', source: (r) => slugify(r.name) },
  { table: 'drug_classes', entity: () => 'drug_class', source: (r) => slugify(r.name) },
  { table: 'dosage_forms', entity: () => 'dosage_form', source: (r) => slugify(r.name) },
  { table: 'conditions', entity: () => 'condition', source: (r) => slugify(r.name) },
  {
    table: 'catalogue_tags',
    entity: () => null,
    source: (r) => slugify(r.name),
    scope: (r) => `${r.catalogue}|${r.kind}`,
  },
];

export async function up(knex: Knex): Promise<void> {
  await knex.schema.createTable('slug_backfill_log', (t) => {
    t.bigIncrements('id').unsigned().primary();
    t.string('table_name', 64).notNullable();
    t.bigInteger('row_id').unsigned().notNullable();
    t.string('old_slug', 190).notNullable();
    t.string('new_slug', 190).notNullable();
    t.boolean('added_redirect').notNullable().defaultTo(false);
  });

  for (const cfg of TABLES) {
    const rows = (await knex(cfg.table).select('*').orderBy('id')) as Row[];
    for (const fix of planBackfill(cfg, rows)) {
      await knex(cfg.table).where({ id: fix.id }).update({ slug: fix.slug });
      if (fix.entity && fix.old)
        await knex('slug_redirects')
          .insert({ entity: fix.entity, old_slug: fix.old, new_slug: fix.slug })
          .onConflict(['entity', 'old_slug'])
          .merge({ new_slug: fix.slug });
      await knex('slug_backfill_log').insert({
        table_name: cfg.table,
        row_id: fix.id,
        old_slug: fix.old,
        new_slug: fix.slug,
        added_redirect: !!(fix.entity && fix.old),
      });
    }
  }
}

/** Pure planning step (unit-tested): which rows get which new slug. */
export function planBackfill(cfg: Table, rows: Row[]) {
  const key = (r: Row, slug: string) => (cfg.scope ? `${cfg.scope(r)}|${slug}` : slug);
  const used = new Set(rows.filter((r) => VALID.test(r.slug ?? '')).map((r) => key(r, r.slug)));
  const fixes: { id: string; old: string; slug: string; entity: string | null }[] = [];
  for (const r of rows) {
    if (VALID.test(r.slug ?? '')) continue;
    const base = cfg.source(r) || slugify(r.slug ?? '') || `${cfg.table}-${r.id}`;
    let slug = base;
    for (let n = 2; used.has(key(r, slug)); n++) slug = `${base}-${n}`;
    used.add(key(r, slug));
    fixes.push({ id: r.id, old: r.slug ?? '', slug, entity: cfg.entity(r) });
  }
  return fixes;
}

export { TABLES };

export async function down(knex: Knex): Promise<void> {
  const log = (await knex('slug_backfill_log').select('*').orderBy('id', 'desc')) as {
    table_name: string;
    row_id: string;
    old_slug: string;
    new_slug: string;
    added_redirect: number | boolean;
  }[];
  for (const l of log) {
    await knex(l.table_name).where({ id: l.row_id }).update({ slug: l.old_slug });
    if (l.added_redirect)
      await knex('slug_redirects').where({ old_slug: l.old_slug, new_slug: l.new_slug }).del();
  }
  await knex.schema.dropTable('slug_backfill_log');
}
