/**
 * Pure functions: website fake JSON → DB rows. No DB access, so they are unit-tested.
 * Ids in the returned rows are *slugs*; the seed resolves them to numeric ids after insert.
 * Prices/doses are copied as-is (NULL / placeholders) — never invented (BACKEND.md §10).
 */
import { SECTION_TO_DB, INFO_KEYS } from './sections';
import { slugify } from '../lib/slug';
import type {
  SiteBrand,
  SiteCompany,
  SiteCondition,
  SiteDosageForm,
  SiteDrugClassGroup,
  SiteGeneric,
  SiteProduct,
} from '../types/site';

const isoDate = (v: string | null | undefined) => (v && /^\d{4}-\d{2}-\d{2}$/.test(v) ? v : null);

export function companyRows(list: SiteCompany[]) {
  return list.map((c) => ({
    slug: c.slug,
    name: c.name,
    catalogues: c.catalogue.join(','),
    status: 'published',
  }));
}

export function drugClassRows(groups: SiteDrugClassGroup[]) {
  return {
    groups: groups.map((g, i) => ({ slug: g.slug, name: g.name, sort_order: i })),
    classes: groups.flatMap((g) =>
      g.classes.map((c, i) => ({
        slug: c.slug,
        name: c.name,
        description: c.description,
        groupSlug: g.slug,
        sort_order: i,
        status: 'published',
      })),
    ),
  };
}

export function dosageFormRows(list: SiteDosageForm[]) {
  return list.map((f, i) => ({
    slug: f.slug,
    name: f.name,
    icon: f.icon,
    description: f.description,
    match_labels: JSON.stringify(f.match),
    sort_order: i,
  }));
}

export function conditionRows(list: SiteCondition[]) {
  const slugs = new Set(list.map((c) => c.slug));
  return {
    conditions: list.map((c) => ({
      slug: c.slug,
      name: c.name,
      guidance: c.guidance || null,
      status: 'published',
    })),
    // drop links to conditions that don't exist
    related: list.flatMap((c) =>
      c.relatedSlugs
        .filter((r) => slugs.has(r) && r !== c.slug)
        .map((r) => ({ conditionSlug: c.slug, relatedSlug: r })),
    ),
  };
}

export function genericRows(list: SiteGeneric[], knownConditions: Set<string>) {
  const bySlug = new Map(list.map((g) => [g.slug, g]));
  const generics = list.map((g) => ({
    slug: g.slug,
    name: g.name,
    catalogue: g.catalogue,
    classSlug: g.classSlug,
    class_label: g.classLabel ?? null,
    tagline: g.tagline ?? null,
    status: 'published',
    review_status: g.review.status,
    reviewer_name: g.review.status === 'approved' ? (g.review.reviewer ?? null) : null,
    reviewed_at: g.review.status === 'approved' ? isoDate(g.review.date) : null,
    sources: JSON.stringify(g.sources),
  }));
  const info = list.flatMap((g) =>
    INFO_KEYS.filter((k) => g.info[k]?.en || g.info[k]?.bn).map((k) => ({
      genericSlug: g.slug,
      section: SECTION_TO_DB[k],
      body_en: g.info[k].en ?? '',
      body_bn: g.info[k].bn ?? null,
    })),
  );
  const conditions = list.flatMap((g) =>
    g.conditionSlugs
      .filter((c) => knownConditions.has(c))
      .map((c) => ({ genericSlug: g.slug, conditionSlug: c })),
  );
  // "Paracetamol + Caffeine" → components that exist as generics (paracetamol)
  const components = list
    .filter((g) => g.name.includes('+'))
    .flatMap((g) =>
      g.name
        .split('+')
        .map((part) => slugify(part))
        .filter((s) => bySlug.has(s) && s !== g.slug)
        .map((s) => ({ combinationSlug: g.slug, componentSlug: s })),
    );
  return { generics, info, conditions, components };
}

/** Brand family = same brand name + company + form label → strength selector siblings. */
export const familyKey = (b: { name: string; companySlug: string; form: string }) =>
  b.name.startsWith('[') ? null : slugify(`${b.name} ${b.companySlug} ${b.form}`);

export function brandRows(list: SiteBrand[], forms: SiteDosageForm[]) {
  const formFor = (label: string) => forms.find((f) => f.match.includes(label))?.slug ?? null;
  const brands = list.map((b) => ({
    slug: b.slug,
    name: b.name,
    genericSlug: b.genericSlug,
    companySlug: b.companySlug,
    dosageFormSlug: formFor(b.form),
    catalogue: b.catalogue,
    form_label: b.form,
    form_icon: b.formIcon,
    strength: b.strength,
    family_key: familyKey(b),
    pack_label: b.pack,
    unit_price: b.unitPrice,
    pack_price: b.packPrice,
    price_updated_at: isoDate(b.priceUpdated),
    price_source: 'DGDA',
    popularity: b.popularity ?? 0,
    status: 'published',
    added_at: isoDate(b.addedAt) ?? '2026-01-01',
  }));
  const formInfo = list.flatMap((b) =>
    INFO_KEYS.filter((k) => b.formInfo?.[k]?.en || b.formInfo?.[k]?.bn).map((k) => ({
      brandSlug: b.slug,
      section: SECTION_TO_DB[k],
      body_en: b.formInfo![k]!.en ?? '',
      body_bn: b.formInfo![k]!.bn ?? null,
    })),
  );
  // The fake data marks "has a pack photo" with an empty URL placeholder.
  const images = list
    .filter((b) => b.packImage)
    .map((b) => ({
      brandSlug: b.slug,
      r2_key: `seed/${b.slug}`,
      url: b.packImage!.url,
      mime: 'image/jpeg',
      credit: b.packImage!.credit,
      photo_date: isoDate(b.packImage!.date),
    }));
  return { brands, formInfo, images };
}

/** Vet/agro tags (Q3): animals, crops and product types, per catalogue. */
export const VET_ANIMALS: [string, string][] = [
  ['cattle', 'Cattle'],
  ['goat-sheep', 'Goat & sheep'],
  ['poultry', 'Poultry'],
  ['fish', 'Fish'],
  ['dogs-cats', 'Dogs & cats'],
];
export const AGRO_CROPS: [string, string][] = [
  ['rice', 'Rice'],
  ['vegetables', 'Vegetables'],
  ['potato', 'Potato'],
  ['jute', 'Jute'],
  ['fruit-trees', 'Fruit trees'],
];
export const VET_TYPES = ['Antibiotics', 'Dewormers', 'Vitamins & minerals', 'Pain & fever', 'Vaccines'];
export const AGRO_TYPES = [
  'Insecticides',
  'Fungicides',
  'Herbicides',
  'Fertilisers & micronutrients',
  'Plant growth regulators',
];

export function catalogueTagRows() {
  return [
    ...VET_ANIMALS.map(([slug, name], i) => ({
      slug,
      name,
      kind: 'animal',
      catalogue: 'vet',
      sort_order: i,
    })),
    ...VET_TYPES.map((name, i) => ({
      slug: slugify(name),
      name,
      kind: 'product_type',
      catalogue: 'vet',
      sort_order: i,
    })),
    ...AGRO_CROPS.map(([slug, name], i) => ({ slug, name, kind: 'crop', catalogue: 'agro', sort_order: i })),
    ...AGRO_TYPES.map((name, i) => ({
      slug: slugify(name),
      name,
      kind: 'product_type',
      catalogue: 'agro',
      sort_order: i,
    })),
  ];
}

/** Vet/agro products become brands (no generic row; the ingredient is kept as a label) + tags. */
export function productRows(list: SiteProduct[], forms: SiteDosageForm[]) {
  const formFor = (label: string) => forms.find((f) => f.match.includes(label))?.slug ?? null;
  const brands = list.map((p) => ({
    slug: p.slug,
    name: p.name,
    genericSlug: null as string | null,
    ingredient_label: p.genericName,
    companySlug: p.companySlug,
    dosageFormSlug: formFor(p.form),
    catalogue: p.catalogue,
    form_label: p.form,
    form_icon: p.formIcon,
    strength: p.strength,
    family_key: null,
    pack_label: null,
    unit_price: null,
    pack_price: null,
    price_updated_at: null,
    price_source: 'DGDA',
    popularity: 0,
    status: 'published',
    added_at: '2026-01-01',
  }));
  const tags = list.flatMap((p) => [
    ...p.animalsOrCrops.map((t) => ({
      brandSlug: p.slug,
      catalogue: p.catalogue,
      kind: p.catalogue === 'vet' ? 'animal' : 'crop',
      tagSlug: t,
    })),
    { brandSlug: p.slug, catalogue: p.catalogue, kind: 'product_type', tagSlug: slugify(p.type) },
  ]);
  return { brands, tags };
}

export const DEFAULT_SETTINGS: Record<string, unknown> = {
  siteUrl: 'https://www.bdmedicine.com',
  contactEmail: '[email address]',
  legalEntity: '[legal entity name]',
  replyDays: 3,
  adsensePublisher: '',
  maintenanceMode: false,
};
