/**
 * Public read queries (Knex, parameter-bound). Only published rows; never prices except brandDetail.
 * Composition (merging medical text, grouping, facets) lives in service.ts.
 */
import type { Knex } from 'knex';
import { db as defaultDb } from '../../db/knex';
import { brandSummaryQuery, orderBrands, type BrandRow } from '../../db/mappers';
import { count, fallbackTerms, likeEscape, prefixRank, whereNameMatches } from '../../db/query';
import { offsetOf, type Pagination } from '../../lib/pagination';
import type { Scope } from './schema';

export type Sort = 'name' | 'popularity' | 'company' | 'newest';
const db = (): Knex => defaultDb;

const inScope = (qb: Knex.QueryBuilder, scope: Scope, col = 'b.catalogue') => {
  if (scope !== 'all') qb.where(col, scope);
};

/* ---------------- search ---------------- */
async function querySuggestBrands(term: string, scope: Scope, limit: number) {
  const qb = brandSummaryQuery(db()).whereNot('b.name', 'like', '[%');
  whereNameMatches(qb, 'b.name', term);
  inScope(qb, scope);
  const [rank, binds] = prefixRank('b.name', term);
  return (await qb
    .orderByRaw(rank, binds)
    .orderByRaw('CHAR_LENGTH(b.name) ASC')
    .orderBy('b.popularity', 'desc')
    .orderBy('b.name', 'asc')
    .orderBy('b.strength', 'asc')
    .limit(limit)) as BrandRow[];
}

export async function suggestBrands(q: string, scope: Scope, limit: number) {
  const direct = await querySuggestBrands(q, scope, limit);
  if (direct.length > 0) return direct;

  // Typo / extra-letter fallback ("fexooos" → "fexo", "napaaaaxs" → "napa")
  for (const term of fallbackTerms(q)) {
    const rows = await querySuggestBrands(term, scope, limit);
    if (rows.length > 0) return rows;
  }

  // Phonetic fallback ("paracetmol", "nappa", etc.)
  const qb = brandSummaryQuery(db())
    .whereNot('b.name', 'like', '[%')
    .whereRaw('SOUNDEX(b.name) = SOUNDEX(?)', [q.trim()]);
  inScope(qb, scope);
  return (await qb
    .orderByRaw('CHAR_LENGTH(b.name) ASC')
    .orderBy('b.popularity', 'desc')
    .orderBy('b.name', 'asc')
    .limit(limit)) as BrandRow[];
}

async function querySuggestGenerics(term: string, scope: Scope, limit: number) {
  const qb = db()('generics as g')
    .leftJoin('drug_classes as dc', 'dc.id', 'g.drug_class_id')
    .select('g.id', 'g.slug', 'g.name', 'g.tagline', 'dc.name as class_name')
    .where('g.status', 'published');
  whereNameMatches(qb, 'g.name', term);
  if (scope !== 'all') qb.where('g.catalogue', scope);
  const [rank, binds] = prefixRank('g.name', term);
  return qb
    .orderByRaw(rank, binds)
    .orderByRaw('CHAR_LENGTH(g.name) ASC')
    .orderBy('g.name', 'asc')
    .limit(limit);
}

export async function suggestGenerics(q: string, scope: Scope, limit: number) {
  const direct = await querySuggestGenerics(q, scope, limit);
  if (direct.length > 0) return direct;

  for (const term of fallbackTerms(q)) {
    const rows = await querySuggestGenerics(term, scope, limit);
    if (rows.length > 0) return rows;
  }

  const qb = db()('generics as g')
    .leftJoin('drug_classes as dc', 'dc.id', 'g.drug_class_id')
    .select('g.id', 'g.slug', 'g.name', 'g.tagline', 'dc.name as class_name')
    .where('g.status', 'published')
    .whereRaw('SOUNDEX(g.name) = SOUNDEX(?)', [q.trim()]);
  if (scope !== 'all') qb.where('g.catalogue', scope);
  return qb.orderByRaw('CHAR_LENGTH(g.name) ASC').orderBy('g.name', 'asc').limit(limit);
}

async function querySearchBrands(term: string, scope: Scope, p: Pagination) {
  const qb = brandSummaryQuery(db()).whereNot('b.name', 'like', '[%');
  qb.where((w) => {
    whereNameMatches(w, 'b.name', term);
    w.orWhere('g.name', 'like', `${likeEscape(term.trim())}%`).orWhere(
      'c.name',
      'like',
      `${likeEscape(term.trim())}%`,
    );
  });
  inScope(qb, scope);
  const total = await count(qb);
  if (total === 0) return { rows: [] as BrandRow[], total: 0 };
  const [rank, binds] = prefixRank('b.name', term);
  const rows = (await qb
    .orderByRaw(rank, binds)
    .orderByRaw('CHAR_LENGTH(b.name) ASC')
    .orderBy('b.popularity', 'desc')
    .orderBy('b.name', 'asc')
    .orderBy('b.strength', 'asc')
    .offset(offsetOf(p))
    .limit(p.pageSize)) as BrandRow[];
  return { rows, total };
}

/** Brands matching by brand name, generic name or company name (full results page). */
export async function searchBrands(q: string, scope: Scope, p: Pagination) {
  const direct = await querySearchBrands(q, scope, p);
  if (direct.total > 0) return direct;

  for (const term of fallbackTerms(q)) {
    const res = await querySearchBrands(term, scope, p);
    if (res.total > 0) return res;
  }

  const qb = brandSummaryQuery(db())
    .whereNot('b.name', 'like', '[%')
    .whereRaw('SOUNDEX(b.name) = SOUNDEX(?)', [q.trim()]);
  inScope(qb, scope);
  const total = await count(qb);
  if (total === 0) return { rows: [] as BrandRow[], total: 0 };
  const rows = (await qb
    .orderByRaw('CHAR_LENGTH(b.name) ASC')
    .orderBy('b.popularity', 'desc')
    .orderBy('b.name', 'asc')
    .offset(offsetOf(p))
    .limit(p.pageSize)) as BrandRow[];
  return { rows, total };
}

/** "Did you mean": sound-alike names (SOUNDEX works on MySQL and MariaDB). */
export async function soundAlike(q: string) {
  const brands = await db()('brands as b')
    .join('generics as g', 'g.id', 'b.generic_id')
    .select('b.slug', 'b.name', 'b.form_icon', 'g.name as generic_name')
    .where('b.status', 'published')
    .whereNot('b.name', 'like', '[%')
    .whereRaw('SOUNDEX(b.name) = SOUNDEX(?)', [q])
    .orderBy('b.popularity', 'desc')
    .limit(1);
  const generics = await db()('generics')
    .select('slug', 'name')
    .where('status', 'published')
    .where((w) =>
      w.whereRaw('SOUNDEX(name) = SOUNDEX(?)', [q]).orWhere('name', 'like', `${likeEscape(q.slice(0, 3))}%`),
    )
    .orderBy('name')
    .limit(2);
  return { brands, generics };
}

/* ---------------- A–Z ---------------- */
export async function brandsByLetter(letter: string, p: Pagination) {
  const qb = brandSummaryQuery(db())
    .where('b.catalogue', 'human')
    .whereNot('b.name', 'like', '[%')
    .where('b.name', 'like', `${letter}%`);
  const total = await count(qb);
  const rows = (await orderBrands(qb, 'name').offset(offsetOf(p)).limit(p.pageSize)) as BrandRow[];
  const totalAll = await count(
    brandSummaryQuery(db()).where('b.catalogue', 'human').whereNot('b.name', 'like', '[%'),
  );
  return { rows, total, totalAll };
}

const genericBase = () =>
  db()('generics as g')
    .leftJoin('drug_classes as dc', 'dc.id', 'g.drug_class_id')
    .leftJoin('reviewers as rv', 'rv.id', 'g.reviewer_id')
    .select(
      'g.id',
      'g.slug',
      'g.name',
      'g.tagline',
      'g.class_label',
      'g.catalogue',
      'g.review_status',
      'g.reviewer_name',
      'g.reviewed_at',
      'g.sources',
      'g.updated_at',
      'rv.slug as reviewer_slug',
      'rv.name as reviewer_display',
      'rv.qualification as reviewer_qualification',
      'g.drug_class_id',
      'g.summary_use_en',
      'g.summary_use_bn',
      'g.summary_dose_en',
      'g.summary_dose_bn',
      'g.summary_how_to_take_en',
      'g.summary_how_to_take_bn',
      'g.summary_safety_en',
      'g.summary_safety_bn',
      'g.food_timing',
      'g.prescription',
      'g.structure_image_url',
      'g.chemical_info',
      'dc.slug as class_slug',
      'dc.name as class_name',
    )
    .select(
      db().raw(
        "(select count(*) from brands b2 where b2.generic_id = g.id and b2.status = 'published') as brand_count",
      ),
    )
    .where('g.status', 'published');

export async function genericsByLetter(letter: string, p: Pagination) {
  const qb = genericBase().where('g.name', 'like', `${letter}%`);
  const total = await count(qb);
  const rows = await qb.orderBy('g.name').offset(offsetOf(p)).limit(p.pageSize);
  const totalAll = await count(genericBase());
  return { rows, total, totalAll };
}

/* ---------------- brand detail ---------------- */
export async function brandBySlug(slug: string) {
  return db()('brands as b')
    .leftJoin('generics as g', 'g.id', 'b.generic_id')
    .join('companies as c', 'c.id', 'b.company_id')
    .leftJoin('drug_classes as dc', 'dc.id', 'g.drug_class_id')
    .leftJoin('reviewers as rv', 'rv.id', 'g.reviewer_id')
    .leftJoin('dosage_forms as df', 'df.id', 'b.dosage_form_id')
    .select(
      'b.*',
      'df.slug as form_slug',
      'df.name as form_name',
      'g.summary_use_en',
      'g.summary_use_bn',
      'g.summary_dose_en',
      'g.summary_dose_bn',
      'g.summary_how_to_take_en',
      'g.summary_how_to_take_bn',
      'g.summary_safety_en',
      'g.summary_safety_bn',
      'g.food_timing',
      'g.prescription',
      'g.structure_image_url',
      'g.chemical_info',
      'rv.slug as reviewer_slug',
      'rv.name as reviewer_display',
      'rv.qualification as reviewer_qualification',
      'g.slug as generic_slug',
      'g.name as generic_name',
      'g.review_status',
      'g.reviewer_name',
      'g.reviewed_at',
      'g.sources',
      'c.slug as company_slug',
      'c.name as company_name',
      'dc.slug as class_slug',
      'dc.name as class_name',
    )
    .where('b.slug', slug)
    .whereIn('b.status', ['published'])
    .first();
}

export const genericInfo = (genericId: string | number) =>
  db()('generic_info').select('section', 'body_en', 'body_bn').where('generic_id', genericId);
export const brandFormInfo = (brandId: string | number) =>
  db()('brand_form_info').select('section', 'body_en', 'body_bn').where('brand_id', brandId);

export async function brandFrontImage(brandId: string | number) {
  return db()('brand_images as bi')
    .join('images as i', 'i.id', 'bi.image_id')
    .select('i.url', 'i.credit', 'i.photo_date', 'i.width', 'i.height', 'i.variants')
    .where('bi.brand_id', brandId)
    .where('i.status', 'published')
    .orderByRaw("CASE WHEN bi.side = 'front' THEN 0 ELSE 1 END")
    .orderBy('bi.sort_order')
    .first();
}

export async function brandAllImages(brandId: string | number) {
  return db()('brand_images as bi')
    .join('images as i', 'i.id', 'bi.image_id')
    .select('i.url', 'i.credit', 'i.photo_date', 'i.width', 'i.height', 'i.variants')
    .where('bi.brand_id', brandId)
    .where('i.status', 'published')
    .orderByRaw("CASE WHEN bi.side = 'front' THEN 0 ELSE 1 END")
    .orderBy('bi.sort_order');
}

export async function familySiblings(familyKey: string) {
  return db()('brands').select('slug', 'strength').where({ family_key: familyKey, status: 'published' });
}

export async function otherBrandsOfGeneric(
  genericId: string | number,
  formLabel: string,
  exceptCompanyId: string | number,
  limit = 12,
) {
  const qb = brandSummaryQuery(db())
    .where('b.generic_id', genericId)
    .where('b.form_label', formLabel)
    .whereNot('b.company_id', exceptCompanyId);
  return (await orderBrands(qb, 'popularity').limit(limit)) as BrandRow[];
}

/* ---------------- generic detail ---------------- */
export const genericBySlug = (slug: string) => genericBase().where('g.slug', slug).first();

export async function genericConditionSlugs(genericId: string | number) {
  const rows = await db()('generic_conditions as gc')
    .join('conditions as c', 'c.id', 'gc.condition_id')
    .select('c.slug')
    .where('gc.generic_id', genericId);
  return rows.map((r: { slug: string }) => r.slug);
}

/** Combinations that contain this generic (e.g. Paracetamol → "Paracetamol + Caffeine"). */
export async function combinationsOf(genericId: string | number) {
  return db()('generic_components as gc')
    .join('generics as g', 'g.id', 'gc.combination_generic_id')
    .select('g.slug', 'g.name')
    .select(
      db().raw(
        "(select count(*) from brands b2 where b2.generic_id = g.id and b2.status = 'published') as brand_count",
      ),
    )
    .where('gc.component_generic_id', genericId)
    .where('g.status', 'published')
    .orderBy('g.name');
}

/** All brands of a generic with their dosage form (for groups, facets, quick facts). */
export async function brandsOfGeneric(genericId: string | number) {
  return (await brandSummaryQuery(db())
    .leftJoin('dosage_forms as df', 'df.id', 'b.dosage_form_id')
    .select(
      'df.slug as form_slug',
      'df.name as form_name',
      'df.icon as form_icon_df',
      'df.sort_order as form_order',
      'c.id as company_id',
    )
    .where('b.generic_id', genericId)) as (BrandRow & {
    form_slug: string | null;
    form_name: string | null;
    form_icon_df: string | null;
    form_order: number | null;
    company_id: string;
  })[];
}

/* ---------------- redirects ---------------- */
export async function redirectFor(entity: string, slug: string) {
  const row = await db()('slug_redirects').select('new_slug').where({ entity, old_slug: slug }).first();
  return row?.new_slug as string | undefined;
}

/* ---------------- medical reviewers (SEO Phase 7) ---------------- */
export const reviewersList = () =>
  db()('reviewers as rv')
    .select('rv.*')
    .select(
      db().raw(
        "(select count(*) from generics g where g.reviewer_id = rv.id and g.status = 'published' and g.review_status = 'approved') as reviewed_count",
      ),
    )
    .where('rv.status', 'published')
    .orderBy('rv.name');

export const reviewerBySlug = (slug: string) =>
  db()('reviewers').select('*').where({ slug, status: 'published' }).first();

/** Generics this reviewer approved (their pages show "Medically reviewed by …"). */
export const genericsReviewedBy = (reviewerId: string | number) =>
  genericBase().where('g.reviewer_id', reviewerId).where('g.review_status', 'approved').orderBy('g.name');

/* ---------------- Phase 8: price table + related generics ---------------- */
/** Every published brand with the same generic, strength and form: cheapest unit price first, unknown prices last. */
export async function alternativesOf(
  genericId: string | number,
  strength: string,
  formLabel: string,
  opts: { limit?: number; offset?: number } = {},
) {
  const base = db()('brands as b').where({
    'b.generic_id': genericId,
    'b.strength': strength,
    'b.form_label': formLabel,
    'b.status': 'published',
  });
  const limit = opts.limit ?? 20;
  const offset = opts.offset ?? 0;
  const [rows, countRow] = await Promise.all([
    base
      .clone()
      .join('companies as c', 'c.id', 'b.company_id')
      .select(
        'b.id',
        'b.slug',
        'b.name',
        'b.pack_label',
        'b.unit_price',
        'b.pack_price',
        'c.slug as company_slug',
        'c.name as company_name',
      )
      .orderByRaw('CASE WHEN b.unit_price IS NULL THEN 1 ELSE 0 END')
      .orderBy('b.unit_price')
      .orderBy('b.name')
      .limit(limit)
      .offset(offset),
    base.clone().count({ n: '*' }).first(),
  ]);
  return { rows, total: Number((countRow as { n?: number | string } | undefined)?.n ?? 0) };
}

/** Other published generics in the same drug class. */
export async function relatedGenerics(classId: string | number, exceptId: string | number) {
  return db()('generics as g')
    .select('g.slug', 'g.name')
    .select(
      db().raw(
        "(select count(*) from brands b2 where b2.generic_id = g.id and b2.status = 'published') as brand_count",
      ),
    )
    .where({ 'g.drug_class_id': classId, 'g.status': 'published' })
    .whereNot('g.id', exceptId)
    .orderBy('g.name')
    .limit(12);
}

/** Conditions a generic is used for, with names (brand page links, SEO Phase 9). */
export const genericConditionRefs = (genericId: string | number) =>
  db()('generic_conditions as gc')
    .join('conditions as c', 'c.id', 'gc.condition_id')
    .select('c.slug', 'c.name')
    .where('gc.generic_id', genericId)
    .where('c.status', 'published')
    .orderBy('c.name');
