import { Router } from 'express';
import type { Knex } from 'knex';
import { z } from 'zod';
import { db } from '../../db/knex';
import { familyKey } from '../../db/seed-mapping';
import { SECTION_FROM_DB, SECTION_TO_DB, INFO_KEYS } from '../../db/sections';
import { notFound, validationError } from '../../lib/http-errors';
import { brandSchema, csvRowSchema } from '../../shared/schemas';
import { brandSlug } from '../../lib/slug';
import { requireRole } from '../../middleware/auth';
import { validate } from '../../middleware/validate';
import { audit, diffOf } from './audit';
import {
  adminPage,
  dosageFormIdForLabel,
  iconForForm,
  idFor,
  idParam,
  paged,
  recordRedirect,
  write,
} from './helpers';

const editors = requireRole('admin', 'editor');

const brandSelect = (q: Knex) =>
  q('brands as b')
    .leftJoin('generics as g', 'g.id', 'b.generic_id')
    .join('companies as c', 'c.id', 'b.company_id')
    .leftJoin('brand_images as bi', function () {
      this.on('bi.brand_id', 'b.id').andOn(q.raw("bi.side = 'front'"));
    })
    .leftJoin('images as i', 'i.id', 'bi.image_id')
    .select(
      'b.*',
      'g.slug as generic_slug',
      'g.name as generic_name',
      'c.slug as company_slug',
      'c.name as company_name',
      'i.id as image_id',
      'i.url as image_url',
      'i.credit as image_credit',
      'i.photo_date as image_date',
    );

/** DB row → the admin's AdminBrand (site Brand + editorial fields). Prices included (admin only). */
function toAdminBrand(
  r: Record<string, unknown>,
  siblings: string[] = [],
  formInfo?: Record<string, unknown>,
) {
  const date = (v: unknown) => (v ? String(v).slice(0, 10) : null);
  return {
    id: String(r.id),
    slug: r.slug,
    name: r.name,
    genericSlug: r.generic_slug ?? '',
    ...(r.generic_name ? { genericName: r.generic_name } : {}),
    companySlug: r.company_slug,
    ...(r.company_name ? { companyName: r.company_name } : {}),
    catalogue: r.catalogue,
    form: r.form_label,
    formIcon: r.form_icon,
    strength: r.strength,
    siblingSlugs: siblings,
    pack: r.pack_label,
    unitPrice: r.unit_price == null ? null : Number(r.unit_price),
    packPrice: r.pack_price == null ? null : Number(r.pack_price),
    priceUpdated: date(r.price_updated_at),
    packImage: r.image_id
      ? { id: String(r.image_id), url: r.image_url, credit: r.image_credit, date: date(r.image_date) ?? '' }
      : null,
    ...(formInfo && Object.keys(formInfo).length ? { formInfo } : {}),
    addedAt: date(r.added_at),
    popularity: Number(r.popularity ?? 0),
    status: r.discontinued_at ? 'discontinued' : r.status,
    darNumber: r.dar_number ?? null,
    updatedAt: r.updated_at,
  };
}

async function loadBrand(id: string) {
  const r = await brandSelect(db).where('b.id', id).first();
  if (!r) throw notFound('Medicine not found.');
  const siblings = r.family_key
    ? (await db('brands').select('slug').where({ family_key: r.family_key })).map(
        (s: { slug: string }) => s.slug,
      )
    : [r.slug];
  const fi = await db('brand_form_info').select('section', 'body_en', 'body_bn').where('brand_id', id);
  const formInfo = Object.fromEntries(
    fi.map((x: { section: string; body_en: string; body_bn: string | null }) => [
      SECTION_FROM_DB[x.section],
      { en: x.body_en, ...(x.body_bn ? { bn: x.body_bn } : {}) },
    ]),
  );
  return toAdminBrand(r, siblings, formInfo);
}

type BrandBody = z.output<typeof brandSchema>;

async function saveBrand(trx: Knex.Transaction, body: BrandBody, adminId: string, existingId?: string) {
  const genericId = await idFor(trx, 'generics', body.genericSlug);
  const companyId = await idFor(trx, 'companies', body.companySlug);
  const fieldErrors: Record<string, string[]> = {};
  if (!genericId) fieldErrors.genericSlug = ['Unknown generic'];
  if (!companyId) fieldErrors.companySlug = ['Unknown company'];
  const clash = await trx('brands')
    .select('id')
    .where({ slug: body.slug })
    .modify((q) => existingId && q.whereNot('id', existingId))
    .first();
  if (clash)
    fieldErrors.slug = [
      'Another medicine already uses this slug. Add the company, e.g. -beximco (SEO.md §1).',
    ];
  if (Object.keys(fieldErrors).length) throw validationError(fieldErrors);

  const before = existingId ? await trx('brands').where({ id: existingId }).first() : undefined;
  const row = {
    slug: body.slug,
    name: body.name,
    generic_id: genericId,
    company_id: companyId,
    catalogue: body.catalogue,
    dosage_form_id: await dosageFormIdForLabel(trx, body.form),
    form_label: body.form,
    form_icon: body.formIcon,
    strength: body.strength,
    family_key: familyKey({ name: body.name, companySlug: body.companySlug, form: body.form }),
    pack_label: body.pack || null,
    unit_price: body.unitPrice,
    pack_price: body.packPrice,
    price_updated_at: body.priceUpdated || null,
    status: body.status === 'discontinued' ? 'published' : body.status,
    discontinued_at:
      body.status === 'discontinued'
        ? (before?.discontinued_at ?? new Date().toISOString().slice(0, 10))
        : null,
    added_at: body.addedAt,
  };
  let id = existingId;
  if (existingId) {
    await trx('brands').where({ id: existingId }).update(row);
    if (before && before.slug !== body.slug) await recordRedirect(trx, 'brand', before.slug, body.slug);
  } else [id] = await trx('brands').insert(row);

  // form-specific info: replace with the non-empty sections
  await trx('brand_form_info').where({ brand_id: id }).del();
  const infoRows = INFO_KEYS.filter((k) => body.formInfo[k].en || body.formInfo[k].bn).map((k) => ({
    brand_id: id,
    section: SECTION_TO_DB[k],
    body_en: body.formInfo[k].en,
    body_bn: body.formInfo[k].bn || null,
  }));
  if (infoRows.length) await trx('brand_form_info').insert(infoRows);

  await audit(
    {
      adminId,
      action: existingId ? 'updated' : 'created',
      entity: 'brand',
      entityId: id,
      label: `${body.name} ${body.strength} ${body.form}`,
      diff: diffOf(before, row),
    },
    trx,
  );
  return String(id);
}

export function brandsRouter() {
  const r = Router();
  const listQuery = adminPage.extend({
    catalogue: z.enum(['human', 'vet', 'agro']).optional(),
    company: z.string().max(140).optional(),
    status: z
      .enum(['draft', 'published', 'discontinued', 'archived', 'active', 'noprice', 'noimage'])
      .optional(),
  });

  r.get('/brands', validate({ query: listQuery }), async (_req, res) => {
    const q = res.locals.valid!.query as z.infer<typeof listQuery>;
    const qb = brandSelect(db).orderByRaw("CASE WHEN b.name LIKE '[%' THEN 1 ELSE 0 END").orderBy('b.name');
    if (q.q)
      qb.where((w) =>
        w
          .where('b.name', 'like', `%${q.q}%`)
          .orWhere('g.name', 'like', `%${q.q}%`)
          .orWhere('c.name', 'like', `%${q.q}%`),
      );
    if (q.catalogue) qb.where('b.catalogue', q.catalogue);
    if (q.company) qb.where('c.slug', q.company);
    if (q.status === 'noprice') qb.whereNull('b.unit_price');
    else if (q.status === 'noimage') qb.whereNull('i.id');
    else if (q.status === 'discontinued') qb.whereNotNull('b.discontinued_at');
    else if (q.status)
      qb.where('b.status', q.status === 'active' ? 'published' : q.status).whereNull('b.discontinued_at');
    res.json(await paged(qb, q, (row: never) => toAdminBrand(row)));
  });

  r.get('/brands/export.csv', async (_req, res) => {
    const rows = await brandSelect(db)
      .leftJoin('generics as g2', 'g2.id', 'b.generic_id')
      .select('g2.name as generic_name', 'c.name as company_name')
      .orderBy('b.name');
    const cols = [
      'name',
      'generic',
      'company',
      'form',
      'strength',
      'catalogue',
      'pack',
      'unit_price',
      'pack_price',
      'price_updated',
      'slug',
    ];
    const esc = (v: unknown) => {
      const s = v == null ? '' : String(v);
      return /[",\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
    };
    const lines = rows.map((b: Record<string, unknown>) =>
      [
        b.name,
        b.generic_name ?? b.ingredient_label,
        b.company_name,
        b.form_label,
        b.strength,
        b.catalogue,
        b.pack_label,
        b.unit_price,
        b.pack_price,
        b.price_updated_at ? String(b.price_updated_at).slice(0, 10) : '',
        b.slug,
      ]
        .map(esc)
        .join(','),
    );
    res
      .set('Content-Type', 'text/csv; charset=utf-8')
      .set('Content-Disposition', 'attachment; filename="bdmedicine-medicines.csv"');
    res.send(`\uFEFF${cols.join(',')}\n${lines.join('\n')}`);
  });

  r.get('/brands/:id', validate({ params: idParam }), async (_req, res) =>
    res.json(await loadBrand(res.locals.valid!.params.id as string)),
  );

  r.post('/brands', editors, validate({ body: brandSchema }), async (_req, res) => {
    const id = await write((trx) =>
      saveBrand(trx, res.locals.valid!.body as BrandBody, res.locals.admin!.id),
    );
    res.status(201).json(await loadBrand(id));
  });

  r.put('/brands/:id', editors, validate({ params: idParam, body: brandSchema }), async (_req, res) => {
    const id = res.locals.valid!.params.id as string;
    if (!(await db('brands').where({ id }).first())) throw notFound('Medicine not found.');
    await write((trx) => saveBrand(trx, res.locals.valid!.body as BrandBody, res.locals.admin!.id, id));
    res.json(await loadBrand(id));
  });

  const deleteMany = async (ids: string[], adminId: string) =>
    write(async (trx) => {
      const rows = await trx('brands').select('id', 'name', 'strength', 'form_label').whereIn('id', ids);
      await trx('brands').whereIn('id', ids).del();
      for (const b of rows)
        await audit(
          {
            adminId,
            action: 'deleted',
            entity: 'brand',
            entityId: b.id,
            label: `${b.name} ${b.strength} ${b.form_label}`,
          },
          trx,
        );
      return rows.length;
    });

  r.delete('/brands/:id', editors, validate({ params: idParam }), async (_req, res) => {
    const n = await deleteMany([res.locals.valid!.params.id as string], res.locals.admin!.id);
    if (!n) throw notFound('Medicine not found.');
    res.status(204).end();
  });

  r.delete(
    '/brands',
    editors,
    validate({ body: z.object({ ids: z.array(z.string().regex(/^\d+$/)).min(1).max(500) }) }),
    async (_req, res) => {
      const n = await deleteMany((res.locals.valid!.body as { ids: string[] }).ids, res.locals.admin!.id);
      res.json({ deleted: n });
    },
  );

  /* ---------- CSV import (rows parsed in the browser; validated again here) ---------- */
  const importBody = z.object({ rows: z.array(z.record(z.string(), z.string())).min(1).max(5000) });
  r.post(
    '/brands/import',
    editors,
    validate({ body: importBody, query: z.object({ dryRun: z.enum(['0', '1']).default('0') }) }),
    async (_req, res) => {
      const { rows } = res.locals.valid!.body as z.infer<typeof importBody>;
      const dryRun = (res.locals.valid!.query as { dryRun: string }).dryRun === '1';
      const generics = new Map(
        (await db('generics').select('name', 'slug')).map((g: { name: string; slug: string }) => [
          g.name.toLowerCase(),
          g.slug,
        ]),
      );
      const companies = new Map(
        (await db('companies').select('name', 'slug')).map((c: { name: string; slug: string }) => [
          c.name.toLowerCase(),
          c.slug,
        ]),
      );
      const schema = csvRowSchema({ generics, companies });
      const existing = new Map(
        (await db('brands').select('id', 'slug', 'company_id')).map((b: { id: string; slug: string }) => [
          b.slug,
          b,
        ]),
      );
      const errors: { line: number; messages: string[] }[] = [];
      const ok: { line: number; body: BrandBody; id?: string }[] = [];
      const seen = new Set<string>();
      rows.forEach((raw, i) => {
        const line = i + 2;
        const p = schema.safeParse(raw);
        if (!p.success) return errors.push({ line, messages: p.error.issues.map((x) => x.message) });
        const v = p.data;
        const slug = brandSlug(v.name === '[Brand]' ? `${v.generic} brand` : v.name, v.strength, v.form);
        if (seen.has(slug))
          return errors.push({ line, messages: ['duplicate of an earlier row in this file'] });
        seen.add(slug);
        const body = brandSchema.safeParse({
          name: v.name,
          slug,
          genericSlug: generics.get(v.generic.toLowerCase()),
          companySlug: companies.get(v.company.toLowerCase()),
          catalogue: v.catalogue,
          form: v.form,
          formIcon: iconForForm(v.form),
          strength: v.strength,
          pack: v.pack,
          unitPrice: v.unit_price,
          packPrice: v.pack_price,
          priceUpdated: v.price_updated,
          status: 'published',
          packImageUrl: '',
          packImageCredit: '',
          addedAt: new Date().toISOString().slice(0, 10),
          formInfo: Object.fromEntries(INFO_KEYS.map((k) => [k, { en: '', bn: '' }])),
        });
        if (!body.success)
          return errors.push({
            line,
            messages: body.error.issues.map((x) => `${x.path.join('.')}: ${x.message}`),
          });
        ok.push({ line, body: body.data, id: (existing.get(slug) as { id?: string } | undefined)?.id });
      });
      const created = ok.filter((x) => !x.id).length;
      const updated = ok.length - created;
      if (!dryRun && ok.length) {
        await write(async (trx) => {
          for (const x of ok) {
            // keep the existing icon / form info / image when updating
            if (x.id) {
              const cur = await trx('brands').select('form_icon').where({ id: x.id }).first();
              const fi = await trx('brand_form_info').where({ brand_id: x.id });
              for (const f of fi)
                x.body.formInfo[SECTION_FROM_DB[f.section]] = { en: f.body_en, bn: f.body_bn ?? '' };
              x.body.formIcon = cur.form_icon;
            }
            await saveBrand(trx, x.body, res.locals.admin!.id, x.id);
          }
          await audit(
            {
              adminId: res.locals.admin!.id,
              action: 'imported',
              entity: 'brand',
              label: `${created} added, ${updated} updated from CSV`,
            },
            trx,
          );
        });
      }
      res.json({ dryRun, created, updated, skipped: errors.length, errors });
    },
  );

  return r;
}
