/**
 * Sitemap rows from MySQL. Same "indexable" rules as the pages:
 * - brands: human catalogue, published, real name (not "[Brand]"), generic published and pharmacist-approved
 * - Bangla page exists when the Indications text has Bangla: the brand's own form-specific text if it
 *   has one, otherwise the generic's (the same merge the brand page uses)
 * - generics: published + approved · companies: published, real name · indications: with guidance text
 * - drug classes: only with at least one published generic (an empty class page is noindex)
 */
import type { Knex } from 'knex';
import { db as defaultDb } from '../db/knex';
import type { SitemapRow, SitemapSource } from './sitemap';

const day = (v: unknown) => (v ? new Date(v as string).toISOString().slice(0, 10) : null);
const filled = (v: unknown) => typeof v === 'string' && v.trim() !== '';

export function createDbSitemapSource(db: () => Knex = () => defaultDb): SitemapSource {
  return {
    async brands() {
      const rows = await db()('brands as b')
        .join('generics as g', 'g.id', 'b.generic_id')
        .leftJoin('brand_images as bi', function () {
          this.on('bi.brand_id', 'b.id').andOn(db().raw("bi.side = 'front'"));
        })
        .leftJoin('images as i', function () {
          this.on('i.id', 'bi.image_id').andOn(db().raw("i.status = 'published'"));
        })
        .leftJoin('brand_form_info as own', function () {
          this.on('own.brand_id', 'b.id').andOn(db().raw("own.section = 'indications'"));
        })
        .leftJoin('generic_info as gi', function () {
          this.on('gi.generic_id', 'g.id').andOn(db().raw("gi.section = 'indications'"));
        })
        .select(
          'b.slug',
          'b.updated_at',
          'i.url as image',
          'own.id as own_id',
          'own.body_bn as own_bn',
          'gi.body_bn as generic_bn',
        )
        .where({ 'b.catalogue': 'human', 'b.status': 'published', 'g.status': 'published' })
        .where('g.review_status', 'approved')
        .whereNot('b.name', 'like', '[%')
        .orderBy('b.slug');
      return rows.map((r: Record<string, unknown>): SitemapRow => ({
        slug: r.slug as string,
        lastmod: day(r.updated_at),
        image: (r.image as string | null) ?? null,
        bn: r.own_id ? filled(r.own_bn) : filled(r.generic_bn),
      }));
    },
    async generics() {
      const rows = await db()('generics as g')
        .leftJoin('generic_info as gi', function () {
          this.on('gi.generic_id', 'g.id').andOn(db().raw("gi.section = 'indications'"));
        })
        .select('g.slug', 'g.updated_at', 'gi.body_bn')
        .where({ 'g.status': 'published', 'g.review_status': 'approved' })
        .orderBy('g.slug');
      return rows.map((r: Record<string, unknown>) => ({
        slug: r.slug as string,
        lastmod: day(r.updated_at),
        bn: filled(r.body_bn),
      }));
    },
    companies: () => simple(db()('companies').where({ status: 'published' }).whereNot('name', 'like', '[%')),
    // a class page without generics is noindex, so it stays out of the sitemap
    drugClasses: () =>
      simple(
        db()('drug_classes as dc')
          .where({ 'dc.status': 'published' })
          .whereExists(
            db()('generics as g').whereRaw('g.drug_class_id = dc.id').where({ 'g.status': 'published' }),
          ),
        'dc.',
      ),
    dosageForms: () => simple(db()('dosage_forms')),
    async catalogueProducts(cat) {
      const rows = await db()('brands as b')
        .leftJoin('brand_images as bi', function () {
          this.on('bi.brand_id', 'b.id').andOn(db().raw("bi.side = 'front'"));
        })
        .leftJoin('images as i', 'i.id', 'bi.image_id')
        .select('b.slug', 'b.updated_at', 'i.url as image')
        .where({ 'b.catalogue': cat, 'b.status': 'published' })
        .whereNot('b.name', 'like', '[%')
        .orderBy('b.slug');
      return rows.map((r: Record<string, unknown>) => ({
        slug: r.slug as string,
        lastmod: day(r.updated_at),
        image: (r.image as string | null) ?? null,
      }));
    },
    reviewers: () => simple(db()('reviewers').where({ status: 'published' }).whereNot('name', 'like', '[%')),
    indications: () =>
      simple(
        db()('conditions').where({ status: 'published' }).whereNotNull('guidance').whereNot('guidance', ''),
      ),
  };
}

async function simple(qb: Knex.QueryBuilder, prefix = ''): Promise<SitemapRow[]> {
  const rows = await qb
    .select(`${prefix}slug as slug`, `${prefix}updated_at as updated_at`)
    .orderBy(`${prefix}slug`);
  return rows.map((r: { slug: string; updated_at: unknown }) => ({
    slug: r.slug,
    lastmod: day(r.updated_at),
  }));
}
