/**
 * Validation rules shared by the admin UI (admin-dashboard, via the `@shared` alias) and the API.
 * Single source of truth (contract Q8): edit here, both sides follow.
 */
import { z } from 'zod';

/* ---------- shared pieces ---------- */
const slug = z
  .string()
  .trim()
  .min(2, 'Slug is required')
  .max(120, 'Keep the slug under 120 characters')
  .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, 'Use lowercase letters, numbers and single hyphens only');

const optionalText = (max = 2000) => z.string().trim().max(max, `Keep this under ${max} characters`);
const lang = z.object({ en: optionalText(4000), bn: optionalText(4000) });

export const CATALOGUES = ['human', 'vet', 'agro'] as const;
export const FORM_ICONS = [
  'tablet',
  'capsule',
  'syrup',
  'suspension',
  'drops',
  'injection',
  'iv',
  'suppository',
  'cream',
  'powder',
] as const;
export const INFO_KEYS = [
  'indications',
  'dosage',
  'sideEffects',
  'precautions',
  'pregnancy',
  'contraindications',
  'interactions',
  'pharmacology',
  'overdose',
  'storage',
  'specialPopulations',
  'patientCounseling',
] as const;

/** Empty input → null; otherwise a non-negative number with up to 2 decimals. Prices are never invented. */
const price = z
  .union([z.literal(''), z.null(), z.coerce.number({ message: 'Enter a number' })])
  .transform((v) => (v === '' || v === null ? null : v))
  .refine((v) => v === null || (v >= 0 && v < 1_000_000), 'Enter a price between 0 and 999,999')
  .refine((v) => v === null || Math.round(v * 100) === v * 100, 'Use at most 2 decimal places');

const isoDate = z.union([
  z.literal(''),
  z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Use the date picker (YYYY-MM-DD)'),
]);

/* ---------- auth ---------- */
export const loginSchema = z.object({
  email: z.string().trim().min(1, 'Enter your email').email('Enter a valid email address'),
  password: z.string().min(8, 'Password must be at least 8 characters'),
  remember: z.boolean(),
});
export type LoginValues = z.infer<typeof loginSchema>;

export const forgotSchema = z.object({
  email: z.string().trim().min(1, 'Enter your email').email('Enter a valid email address'),
});

/* ---------- medicine (brand) ---------- */
export const brandSchema = z
  .object({
    name: z
      .string()
      .trim()
      .min(1, 'Brand name is required')
      .max(80, 'Keep the brand name under 80 characters'),
    slug,
    genericSlug: z.string().min(1, 'Choose the generic (active ingredient)'),
    companySlug: z.string().min(1, 'Choose the company'),
    catalogue: z.enum(CATALOGUES),
    form: z.string().trim().min(1, 'Dosage form is required').max(60),
    formIcon: z.enum(FORM_ICONS),
    strength: z
      .string()
      .trim()
      .min(1, 'Strength is required, e.g. 500 mg or 120 mg/5 ml')
      .regex(
        /^(\[strength\]|[\d.]+\s?(mg|mcg|g|gm|ml|iu|%)(\s?[+/]\s?[\d.]*\s?(mg|mcg|g|gm|ml|iu|%)?)*)$/i,
        'Use a value and unit, e.g. 500 mg, 120 mg/5 ml, 500 mg + 65 mg',
      ),
    pack: optionalText(120),
    unitPrice: price,
    packPrice: price,
    priceUpdated: isoDate,
    // Q4: draft | published | discontinued | archived. "active" (current admin UI) is accepted as "published" until step 9.
    status: z
      .enum(['draft', 'published', 'discontinued', 'archived', 'active'])
      .transform((v) => (v === 'active' ? 'published' : v)),
    packImageUrl: z.union([
      z.literal(''),
      z.string().regex(/^data:image\/(png|jpe?g|webp);base64,/),
      z.string().url('Enter a full image URL (https://…)'),
    ]),
    packImageCredit: optionalText(120),
    addedAt: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Choose a date'),
    formInfo: z.object(
      Object.fromEntries(INFO_KEYS.map((k) => [k, lang])) as Record<(typeof INFO_KEYS)[number], typeof lang>,
    ),
  })
  .superRefine((v, ctx) => {
    if ((v.unitPrice !== null || v.packPrice !== null) && !v.priceUpdated) {
      ctx.addIssue({
        code: 'custom',
        path: ['priceUpdated'],
        message: 'Add the DGDA price date when a price is entered',
      });
    }
    if (v.packImageUrl && !v.packImageCredit) {
      ctx.addIssue({
        code: 'custom',
        path: ['packImageCredit'],
        message: 'Say who owns the image (company or contributor)',
      });
    }
  });
export type BrandFormInput = z.input<typeof brandSchema>;
export type BrandFormValues = z.output<typeof brandSchema>;

/* ---------- generic ---------- */
const chemicalInfoSchema = z
  .object({
    pubchemCid: z.number().int().positive().nullable().optional(),
    molecularFormula: optionalText(120).nullable().optional(),
    molecularWeight: optionalText(60).nullable().optional(),
    iupacName: optionalText(600).nullable().optional(),
    pubchemUrl: z.union([z.literal(''), z.string().url()]).nullable().optional(),
  })
  .nullable()
  .optional();

const genericFaqSchema = z.object({
  q: z.object({ en: optionalText(500), bn: optionalText(500).optional().default('') }),
  a: z.object({ en: optionalText(2000), bn: optionalText(2000).optional().default('') }),
});

export const genericSchema = z
  .object({
    name: z.string().trim().min(2, 'Generic name is required').max(160),
    slug,
    catalogue: z.enum(CATALOGUES),
    classSlug: z.string().trim(),
    classLabel: optionalText(200),
    classLabelBn: optionalText(200).optional().default(''),
    tagline: optionalText(120),
    structureImageUrl: z
      .union([z.literal(''), z.string().url('Enter a full image URL (https://…)')])
      .optional()
      .default(''),
    chemicalInfo: chemicalInfoSchema,
    faq: z.array(genericFaqSchema).optional().default([]),
    conditionSlugs: z.array(z.string()),
    combinations: z.array(z.string()),
    sources: z.array(z.string()).min(1, 'Choose at least one source'),
    reviewStatus: z.enum(['approved', 'pending']),
    /** slug of a reviewer profile (SEO Phase 7) */
    reviewerSlug: optionalText(160),
    reviewDate: isoDate,
    info: z.object(
      Object.fromEntries(INFO_KEYS.map((k) => [k, lang])) as Record<(typeof INFO_KEYS)[number], typeof lang>,
    ),
    /* quick summary (SEO Phase 8): optional, written by a pharmacist; the site shows only what is filled */
    summaryUse: z.object({ en: optionalText(1000), bn: optionalText(1000) }),
    summaryDose: z.object({ en: optionalText(1000), bn: optionalText(1000) }),
    summaryHowToTake: z
      .object({ en: optionalText(1000), bn: optionalText(1000) })
      .optional()
      .default({ en: '', bn: '' }),
    summarySafety: z
      .object({ en: optionalText(1000), bn: optionalText(1000) })
      .optional()
      .default({ en: '', bn: '' }),
    foodTiming: z.enum(['', 'before', 'after', 'with', 'any']),
    prescription: z.enum(['', 'required', 'not_required']),
  })
  .superRefine((v, ctx) => {
    if (v.reviewStatus === 'approved') {
      if (!v.reviewerSlug)
        ctx.addIssue({
          code: 'custom',
          path: ['reviewerSlug'],
          message: 'An approved page needs the reviewing pharmacist',
        });
      if (!v.reviewDate)
        ctx.addIssue({ code: 'custom', path: ['reviewDate'], message: 'Add the review date' });
      if (!v.info.indications.en)
        ctx.addIssue({
          code: 'custom',
          path: ['info', 'indications', 'en'],
          message: 'Indications are required before approval',
        });
    }
  });
export type GenericFormInput = z.input<typeof genericSchema>;
export type GenericFormValues = z.output<typeof genericSchema>;

/* ---------- medical reviewer (SEO Phase 7) ---------- */
export const reviewerSchema = z.object({
  name: z.string().trim().min(2, 'Name is required').max(160),
  slug,
  qualification: z.string().trim().min(2, 'Add the qualification, e.g. B.Pharm, M.Pharm or MBBS').max(160),
  registrationNo: optionalText(80),
  bio: optionalText(600),
  photoUrl: z.union([z.literal(''), z.string().url('Enter a full image URL (https://…)')]),
});
export type ReviewerFormValues = z.infer<typeof reviewerSchema>;

/* ---------- company ---------- */
export const companySchema = z.object({
  name: z.string().trim().min(2, 'Company name is required').max(120),
  slug,
  catalogue: z.array(z.enum(CATALOGUES)).min(1, 'Choose at least one catalogue'),
});
export type CompanyFormValues = z.infer<typeof companySchema>;

/* ---------- taxonomy ---------- */
export const drugClassSchema = z.object({
  name: z.string().trim().min(2, 'Class name is required').max(120),
  nameBn: optionalText(160).optional().default(''),
  slug,
  groupSlug: z.string().min(1, 'Choose a group'),
  description: optionalText(300),
  descriptionBn: optionalText(350).optional().default(''),
});
export const dosageFormSchema = z.object({
  name: z.string().trim().min(2, 'Name is required').max(80),
  nameBn: optionalText(120).optional().default(''),
  slug,
  icon: z.enum(FORM_ICONS),
  route: optionalText(80).optional().default(''),
  routeBn: optionalText(120).optional().default(''),
  description: optionalText(300),
  descriptionBn: optionalText(350).optional().default(''),
  match: z.string().trim().min(1, 'List at least one brand form, e.g. Tablet'),
});
export const conditionSchema = z.object({
  name: z.string().trim().min(2, 'Name is required').max(80),
  slug,
  guidance: optionalText(300),
  relatedSlugs: z.array(z.string()),
});

/* ---------- vet / agro product ---------- */
export const productSchema = z.object({
  name: z.string().trim().min(1, 'Name is required').max(80),
  slug,
  catalogue: z.enum(['vet', 'agro']),
  type: z.string().min(1, 'Choose a type'),
  animalsOrCrops: z.array(z.string()).min(1, 'Choose at least one animal or crop'),
  form: z.string().trim().min(1, 'Form is required'),
  formIcon: z.enum(FORM_ICONS),
  strength: z.string().trim().min(1, 'Strength is required'),
  genericName: z.string().trim().min(1, 'Active ingredient is required'),
  companySlug: z.string().min(1, 'Choose the company'),
  /* label facts (SEO Phase 12), optional: shown on the product page only when filled */
  withdrawalPeriod: optionalText(200),
  targetPest: optionalText(300),
  doseRate: optionalText(300),
});

/* ---------- users & settings ---------- */
export const userSchema = z.object({
  name: z.string().trim().min(2, 'Name is required').max(80),
  email: z.string().trim().email('Enter a valid email address'),
  role: z.enum(['admin', 'editor', 'pharmacist']),
  status: z.enum(['active', 'invited', 'disabled']),
});

export const settingsSchema = z.object({
  siteUrl: z
    .string()
    .url('Enter the full site URL, e.g. https://www.bdmedicine.com')
    .refine((v) => !v.endsWith('/'), 'Remove the trailing slash'),
  contactEmail: z.string().email('Enter a valid email address').or(z.literal('[email address]')),
  legalEntity: z.string().trim().min(1, 'Required'),
  replyDays: z.coerce.number().int('Whole days only').min(1, 'At least 1 day').max(30, 'At most 30 days'),
  adsensePublisher: z.union([
    z.literal(''),
    z.string().regex(/^pub-\d{16}$/, 'Format: pub- followed by 16 digits'),
  ]),
  maintenanceMode: z.boolean(),
});

/* ---------- CSV import row (medicines) ---------- */
export const CSV_COLUMNS = [
  'name',
  'generic',
  'company',
  'form',
  'strength',
  'catalogue',
  'pack',
  'unit_price',
  'pack_price',
  'price_updated',
] as const;

/** Builds the row schema with lookups so generic/company names are checked against existing records. */
export function csvRowSchema(lookups: { generics: Map<string, string>; companies: Map<string, string> }) {
  return z
    .object({
      name: z.string().trim().min(1, 'name is empty').max(80, 'name is too long'),
      generic: z.string().trim().min(1, 'generic is empty'),
      company: z.string().trim().min(1, 'company is empty'),
      form: z.string().trim().min(1, 'form is empty'),
      strength: z.string().trim().min(1, 'strength is empty'),
      catalogue: z
        .string()
        .trim()
        .toLowerCase()
        .transform((v) => v || 'human')
        .pipe(z.enum(CATALOGUES, { message: 'catalogue must be human, vet or agro' })),
      pack: z.string().trim().max(120).optional().default(''),
      unit_price: z.string().trim().optional().default(''),
      pack_price: z.string().trim().optional().default(''),
      price_updated: z.string().trim().optional().default(''),
    })
    .superRefine((r, ctx) => {
      if (!lookups.generics.has(r.generic.toLowerCase()))
        ctx.addIssue({
          code: 'custom',
          path: ['generic'],
          message: `unknown generic “${r.generic}” (add it first)`,
        });
      if (!lookups.companies.has(r.company.toLowerCase()))
        ctx.addIssue({ code: 'custom', path: ['company'], message: `unknown company “${r.company}”` });
      for (const k of ['unit_price', 'pack_price'] as const) {
        if (r[k] && !/^\d+(\.\d{1,2})?$/.test(r[k]))
          ctx.addIssue({ code: 'custom', path: [k], message: `${k} must be a number like 2.50` });
      }
      if (r.price_updated && !/^\d{4}-\d{2}-\d{2}$/.test(r.price_updated))
        ctx.addIssue({
          code: 'custom',
          path: ['price_updated'],
          message: 'price_updated must be YYYY-MM-DD',
        });
      if ((r.unit_price || r.pack_price) && !r.price_updated)
        ctx.addIssue({
          code: 'custom',
          path: ['price_updated'],
          message: 'price_updated is required when a price is given',
        });
    });
}
