import type { Knex } from 'knex';

/**
 * Initial schema (BACKEND.md §3 + approved contract decisions Q1, Q3–Q6).
 * Works on MySQL 8 and MariaDB 10.6+: InnoDB, utf8mb4_unicode_ci (Bangla text), FKs, FULLTEXT.
 */

export const STATUSES = ['draft', 'published', 'archived'] as const;
export const INFO_SECTIONS = [
  'indications',
  'dosage',
  'side_effects',
  'precautions',
  'pregnancy',
  'contraindications',
  'interactions',
  'pharmacology',
  'overdose',
  'storage',
] as const;
export const FORM_ICONS = [
  'tablet',
  'capsule',
  'syrup',
  'suspension',
  'drops',
  'injection',
  'iv',
  'suppository',
  'cream',
  'powder',
] as const;

function base(t: Knex.CreateTableBuilder, knex: Knex) {
  t.engine('InnoDB');
  t.charset('utf8mb4');
  t.collate('utf8mb4_unicode_ci');
  t.bigIncrements('id').unsigned().primary();
  t.timestamp('created_at').notNullable().defaultTo(knex.fn.now());
  t.timestamp('updated_at')
    .notNullable()
    .defaultTo(knex.raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
}

/** Join tables: composite primary key, no surrogate id. */
function joinBase(t: Knex.CreateTableBuilder) {
  t.engine('InnoDB');
  t.charset('utf8mb4');
  t.collate('utf8mb4_unicode_ci');
}

const fk = (
  t: Knex.CreateTableBuilder,
  col: string,
  table: string,
  onDelete: 'CASCADE' | 'RESTRICT' | 'SET NULL',
  nullable = false,
) => {
  const c = t.bigInteger(col).unsigned();
  if (nullable) c.nullable();
  else c.notNullable();
  t.foreign(col).references('id').inTable(table).onDelete(onDelete).onUpdate('CASCADE');
  t.index([col]);
};

export async function up(knex: Knex): Promise<void> {
  /* ---------- admins (Q1: role + status kept) ---------- */
  await knex.schema.createTable('admins', (t) => {
    base(t, knex);
    t.string('name', 120).notNullable();
    t.string('email', 190).notNullable().unique();
    t.string('password_hash', 100).nullable(); // null while an invite is pending
    t.enum('role', ['admin', 'editor', 'pharmacist']).notNullable().defaultTo('admin');
    t.enum('status', ['active', 'invited', 'disabled']).notNullable().defaultTo('active');
    t.timestamp('last_login_at').nullable();
  });

  /* ---------- catalogue lookups ---------- */
  await knex.schema.createTable('companies', (t) => {
    base(t, knex);
    t.string('slug', 140).notNullable().unique();
    t.string('name', 160).notNullable();
    t.specificType('catalogues', "SET('human','vet','agro')").notNullable().defaultTo('human');
    t.string('website', 255).nullable();
    t.enum('status', STATUSES).notNullable().defaultTo('published');
    t.index(['name']);
    t.index(['name'], 'companies_name_fulltext', { indexType: 'FULLTEXT' });
  });

  await knex.schema.createTable('drug_class_groups', (t) => {
    base(t, knex);
    t.string('slug', 140).notNullable().unique();
    t.string('name', 120).notNullable();
    t.integer('sort_order').notNullable().defaultTo(0);
  });

  await knex.schema.createTable('drug_classes', (t) => {
    base(t, knex);
    t.string('slug', 140).notNullable().unique();
    t.string('name', 120).notNullable();
    fk(t, 'group_id', 'drug_class_groups', 'RESTRICT');
    t.string('description', 300).notNullable().defaultTo('');
    t.integer('sort_order').notNullable().defaultTo(0);
    t.enum('status', STATUSES).notNullable().defaultTo('published');
  });

  await knex.schema.createTable('dosage_forms', (t) => {
    base(t, knex);
    t.string('slug', 140).notNullable().unique();
    t.string('name', 80).notNullable();
    t.enum('icon', FORM_ICONS).notNullable();
    t.string('description', 300).notNullable().defaultTo('');
    t.json('match_labels').notNullable(); // brand form labels that belong to this form, e.g. ["Tablet","Tablet (Extended Release)"]
    t.integer('sort_order').notNullable().defaultTo(0);
  });

  await knex.schema.createTable('conditions', (t) => {
    base(t, knex);
    t.string('slug', 140).notNullable().unique();
    t.string('name', 120).notNullable();
    t.text('guidance').nullable(); // indexed only when written (SEO.md §9)
    t.enum('status', STATUSES).notNullable().defaultTo('published');
    t.index(['name']);
    t.index(['name'], 'conditions_name_fulltext', { indexType: 'FULLTEXT' });
  });

  await knex.schema.createTable('condition_related', (t) => {
    joinBase(t);
    fk(t, 'condition_id', 'conditions', 'CASCADE');
    fk(t, 'related_condition_id', 'conditions', 'CASCADE');
    t.primary(['condition_id', 'related_condition_id']);
  });

  /* ---------- generics ---------- */
  await knex.schema.createTable('generics', (t) => {
    base(t, knex);
    t.string('slug', 160).notNullable().unique();
    t.string('name', 160).notNullable();
    t.enum('catalogue', ['human', 'vet', 'agro']).notNullable().defaultTo('human');
    fk(t, 'drug_class_id', 'drug_classes', 'RESTRICT', true);
    t.string('class_label', 160).nullable();
    t.string('tagline', 120).nullable();
    t.enum('status', STATUSES).notNullable().defaultTo('published');
    t.enum('review_status', ['pending', 'approved']).notNullable().defaultTo('pending');
    t.string('reviewer_name', 160).nullable();
    t.date('reviewed_at').nullable();
    t.json('sources').notNullable();
    t.index(['name']);
    t.index(['review_status']);
    t.index(['name'], 'generics_name_fulltext', { indexType: 'FULLTEXT' });
  });

  await knex.schema.createTable('generic_info', (t) => {
    base(t, knex);
    fk(t, 'generic_id', 'generics', 'CASCADE');
    t.enum('section', INFO_SECTIONS).notNullable();
    t.text('body_en').notNullable();
    t.text('body_bn').nullable();
    t.unique(['generic_id', 'section']);
  });

  await knex.schema.createTable('generic_conditions', (t) => {
    joinBase(t);
    fk(t, 'generic_id', 'generics', 'CASCADE');
    fk(t, 'condition_id', 'conditions', 'CASCADE');
    t.primary(['generic_id', 'condition_id']);
  });

  await knex.schema.createTable('generic_components', (t) => {
    joinBase(t);
    fk(t, 'combination_generic_id', 'generics', 'CASCADE');
    fk(t, 'component_generic_id', 'generics', 'CASCADE');
    t.primary(['combination_generic_id', 'component_generic_id']);
  });

  /* ---------- brands ---------- */
  await knex.schema.createTable('brands', (t) => {
    base(t, knex);
    t.string('slug', 190).notNullable().unique();
    t.string('name', 120).notNullable();
    // Human brands always have a generic (enforced by validation); vet/agro products may only have an ingredient label.
    fk(t, 'generic_id', 'generics', 'RESTRICT', true);
    t.string('ingredient_label', 160).nullable();
    fk(t, 'company_id', 'companies', 'RESTRICT');
    t.enum('catalogue', ['human', 'vet', 'agro']).notNullable().defaultTo('human');
    fk(t, 'dosage_form_id', 'dosage_forms', 'SET NULL', true);
    t.string('form_label', 80).notNullable(); // "Tablet (Extended Release)"
    t.enum('form_icon', FORM_ICONS).notNullable();
    t.string('strength', 80).notNullable(); // "500 mg"
    t.string('family_key', 190).nullable(); // same brand's other strengths/sizes (strength selector)
    t.string('pack_label', 120).nullable();
    t.decimal('unit_price', 10, 2).nullable(); // NULL = unknown, UI shows ৳ [price]
    t.decimal('pack_price', 10, 2).nullable();
    t.date('price_updated_at').nullable();
    t.string('price_source', 40).notNullable().defaultTo('DGDA');
    t.string('dar_number', 60).nullable();
    t.integer('popularity').notNullable().defaultTo(0); // Q6
    t.enum('status', STATUSES).notNullable().defaultTo('published');
    t.date('discontinued_at').nullable(); // Q4: page stays live with a notice
    t.date('added_at').notNullable();
    t.index(['name']);
    t.index(['family_key']);
    t.index(['catalogue', 'status']);
    t.index(['added_at']);
    t.index(['name'], 'brands_name_fulltext', { indexType: 'FULLTEXT' });
  });

  await knex.schema.createTable('brand_form_info', (t) => {
    base(t, knex);
    fk(t, 'brand_id', 'brands', 'CASCADE');
    t.enum('section', INFO_SECTIONS).notNullable();
    t.text('body_en').notNullable();
    t.text('body_bn').nullable();
    t.unique(['brand_id', 'section']);
  });

  /* ---------- images (R2) ---------- */
  await knex.schema.createTable('images', (t) => {
    base(t, knex);
    t.string('r2_key', 255).notNullable().unique();
    t.string('url', 500).notNullable();
    t.string('mime', 40).notNullable();
    t.integer('size_bytes').unsigned().notNullable().defaultTo(0);
    t.integer('width').unsigned().nullable();
    t.integer('height').unsigned().nullable();
    t.string('credit', 160).notNullable();
    t.date('photo_date').nullable();
    t.string('permission_note', 300).nullable();
    t.enum('status', STATUSES).notNullable().defaultTo('published');
  });

  await knex.schema.createTable('brand_images', (t) => {
    joinBase(t);
    fk(t, 'brand_id', 'brands', 'CASCADE');
    fk(t, 'image_id', 'images', 'CASCADE');
    t.enum('side', ['front', 'back']).notNullable().defaultTo('front');
    t.integer('sort_order').notNullable().defaultTo(0);
    t.primary(['brand_id', 'image_id']);
  });

  /* ---------- vet / agro tags (Q3) ---------- */
  await knex.schema.createTable('catalogue_tags', (t) => {
    base(t, knex);
    t.string('slug', 140).notNullable();
    t.string('name', 120).notNullable();
    t.enum('kind', ['animal', 'crop', 'product_type']).notNullable();
    t.enum('catalogue', ['vet', 'agro']).notNullable();
    t.integer('sort_order').notNullable().defaultTo(0);
    t.unique(['catalogue', 'kind', 'slug']);
  });

  await knex.schema.createTable('brand_tags', (t) => {
    joinBase(t);
    fk(t, 'brand_id', 'brands', 'CASCADE');
    fk(t, 'tag_id', 'catalogue_tags', 'CASCADE');
    t.primary(['brand_id', 'tag_id']);
  });

  /* ---------- redirects, messages, audit, settings ---------- */
  await knex.schema.createTable('slug_redirects', (t) => {
    base(t, knex);
    t.enum('entity', [
      'brand',
      'generic',
      'company',
      'drug_class',
      'dosage_form',
      'condition',
      'product',
    ]).notNullable();
    t.string('old_slug', 190).notNullable();
    t.string('new_slug', 190).notNullable();
    t.unique(['entity', 'old_slug']);
  });

  await knex.schema.createTable('contact_messages', (t) => {
    base(t, knex);
    t.string('name', 120).nullable();
    t.string('contact', 190).notNullable();
    t.enum('topic', ['mistake', 'missing', 'photo', 'other']).notNullable(); // matches the website form values
    t.text('message').notNullable();
    t.string('page_ref', 190).nullable();
    t.enum('status', ['new', 'in_progress', 'resolved']).notNullable().defaultTo('new'); // Q5
    t.string('ip_hash', 64).nullable();
    t.index(['status', 'created_at']);
  });

  await knex.schema.createTable('audit_log', (t) => {
    t.engine('InnoDB');
    t.charset('utf8mb4');
    t.collate('utf8mb4_unicode_ci');
    t.bigIncrements('id').unsigned().primary();
    fk(t, 'admin_id', 'admins', 'SET NULL', true);
    t.string('action', 40).notNullable(); // created | updated | deleted | approved | imported | login
    t.string('entity', 40).notNullable();
    t.string('entity_id', 64).nullable();
    t.string('label', 190).nullable(); // human-readable target, e.g. "Napa 500 mg Suppository"
    t.json('diff').nullable();
    t.timestamp('created_at').notNullable().defaultTo(knex.fn.now());
    t.index(['created_at']);
    t.index(['entity', 'entity_id']);
  });

  await knex.schema.createTable('settings', (t) => {
    base(t, knex);
    t.string('key', 80).notNullable().unique();
    t.json('value').notNullable();
  });
}

export async function down(knex: Knex): Promise<void> {
  for (const table of [
    'settings',
    'audit_log',
    'contact_messages',
    'slug_redirects',
    'brand_tags',
    'catalogue_tags',
    'brand_images',
    'images',
    'brand_form_info',
    'brands',
    'generic_components',
    'generic_conditions',
    'generic_info',
    'generics',
    'condition_related',
    'conditions',
    'dosage_forms',
    'drug_classes',
    'drug_class_groups',
    'companies',
    'admins',
  ]) {
    await knex.schema.dropTableIfExists(table);
  }
}
