/**
 * The website's data client for server rendering: same methods and response shapes as the public
 * API (website/src/lib/apiTypes.ts → DataClient), but calls the services directly instead of over HTTP.
 * Inputs go through the same zod schemas as the HTTP routes, so behaviour is identical.
 */
import type { ZodType } from 'zod';
import { HttpError } from '../lib/http-errors';
import { schemas as s } from '../modules/public/schema';
import * as svc from '../modules/public/service';
import * as browse from '../modules/public/browse';

/* eslint-disable @typescript-eslint/no-explicit-any */
type Params = Record<string, unknown>;

/** Same encoding as the browser's remote client: drop empty values, arrays → comma lists. */
const asQuery = (p: Params = {}) =>
  Object.fromEntries(
    Object.entries(p)
      .filter(([, v]) => v !== undefined && v !== '' && !(Array.isArray(v) && v.length === 0))
      .map(([k, v]) => [k, Array.isArray(v) ? v.join(',') : String(v)]),
  );

/** Invalid input on a public page means the page doesn't exist: the website shows its 404 page. */
function parse<T>(schema: ZodType<T>, p: Params): T {
  const r = schema.safeParse(asQuery(p));
  if (!r.success) throw new Response(null, { status: 404, statusText: 'Not Found' });
  return r.data;
}
const slug = (v: string) => parse(s.slugParam, { slug: v }).slug;

/** Detail endpoints answer 404 over HTTP; the website's client turns that into `null`. */
async function orNull<T>(fn: () => Promise<T>): Promise<T | null> {
  try {
    return await fn();
  } catch (e) {
    if (e instanceof HttpError && e.status === 404) return null;
    if (e instanceof Response && e.status === 404) return null;
    throw e;
  }
}

export function createDbClient() {
  return {
    suggest: (q: string, scope: string) => {
      const v = parse(s.suggest, { q, scope });
      return svc.suggest(v.q, v.scope);
    },
    search: (q: Params) => {
      const v = parse(s.search, q);
      return svc.search(v.q, v.scope, v.type, { page: v.page, pageSize: v.pageSize });
    },
    didYouMean: (q: string) => svc.didYouMean(parse(s.didYouMean, { q }).q),
    medicines: (q: Params) => {
      const v = parse(s.letterPage, q);
      return svc.medicinesAZ(v.letter, { page: v.page, pageSize: v.pageSize });
    },
    medicine: (sl: string) => orNull(() => svc.brandDetail(slug(sl))),
    medicineAlternatives: (sl: string, q: Params) => {
      const v = parse(s.alternativesPage, q);
      return svc.brandAlternatives(slug(sl), { page: v.page, pageSize: v.pageSize });
    },
    generics: (q: Params) => {
      const v = parse(s.letterPage, q);
      return svc.genericsAZ(v.letter, { page: v.page, pageSize: v.pageSize });
    },
    generic: (sl: string, form?: string) =>
      orNull(() => svc.genericDetail(slug(sl), parse(s.genericDetail, { form }).form)),
    genericBrands: (sl: string, q: Params) =>
      orNull(() => svc.genericBrands(slug(sl), parse(s.genericBrands, q) as any)),
    companies: (q?: string) => browse.companies(parse(s.companies, { q }).q),
    company: (sl: string, q: Params) =>
      orNull(() => browse.companyDetail(slug(sl), parse(s.companyDetail, q))),
    drugClasses: () => browse.drugClasses(),
    drugClass: (sl: string) => orNull(() => browse.drugClassDetail(slug(sl))),
    dosageForms: () => browse.dosageForms(),
    dosageForm: (sl: string, q: Params) =>
      orNull(() => browse.dosageFormDetail(slug(sl), parse(s.formDetail, q) as any)),
    conditions: (q: Params) => browse.conditions(parse(s.conditions, q)),
    condition: (sl: string) => orNull(() => browse.conditionDetail(slug(sl))),
    reviewers: () => browse.reviewers(),
    reviewer: (sl: string) => orNull(() => browse.reviewerDetail(slug(sl))),
    catalogueProduct: (cat: string, sl: string) =>
      orNull(() => browse.catalogueProduct(parse(s.catalogueParam, { cat }).cat, slug(sl))),
    catalogue: (cat: string, q: Params) =>
      browse.catalogue(parse(s.catalogueParam, { cat }).cat, parse(s.catalogue, q)),
    newMedicines: (q: Params) => {
      const v = parse(s.newMedicines, q);
      return browse.newMedicines(v.period, { page: v.page, pageSize: v.pageSize });
    },
    // the contact form posts from the browser to /api/v1/contact; never called during a render
    contact: async () => {
      throw new Error('contact is not available during server rendering');
    },
  };
}
