import {
  computeHmacSha256Signature,
  verifyHmacSha256Signature,
} from './bridgeSecurity.js';
import type { IncomingOrderQuote } from '../types.js';

export type StorefrontEnvironment = 'staging' | 'production';
export type StorefrontTrack = 'b2b' | 'eczema' | 'menopause' | 'purity';
export type StorefrontSkuKind = 'kit' | 'addon' | 'sample' | 'product' | 'bundle';
export type StorefrontAvailabilityStatus =
  | 'preorder'
  | 'sample_only'
  | 'in_development'
  | 'in_stock'
  | 'sold_out';

export type StorefrontEventType =
  | 'b2b_inquiry'
  | 'b2b_sample_request'
  | 'retail_preorder'
  | 'retail_paid_order'
  | 'ping';

export interface AgreedCatalogSku {
  sku: string;
  storefrontSlug: string;
  variantKey: string;
  track: StorefrontTrack;
  kind: StorefrontSkuKind;
  nameEn: string;
  nameFr: string;
  formatLabel: string;
  priceCad: number;
  status: StorefrontAvailabilityStatus;
  stockAvailable: number;
  cureLeadDays: number;
  cureReadyDate: string | null;
  moq: number;
  unitCogsCad: number;
  deductsMaterials: boolean;
  activeOnStorefront: boolean;
}

export interface StorefrontAgreementCatalog {
  schemaVersion: '1.0.0';
  catalogVersion: number;
  updatedAt: string;
  brandPositioning: {
    primaryFace: 'b2b';
    secondaryTracks: Array<'eczema' | 'menopause'>;
    currency: 'CAD';
    b2bPriorityNote: string;
    taxMode: 'estimated_canadian_provincial';
  };
  products: AgreedCatalogSku[];
}

export interface StorefrontInboundLineItem {
  sku?: string;
  storefrontSlug: string;
  variantKey: string;
  name: string;
  qty: number;
  unitPriceCad: number;
}

export interface StorefrontInboundEvent {
  schemaVersion: 'ljw-storefront-v1';
  idempotencyKey: string;
  environment: StorefrontEnvironment;
  eventType: StorefrontEventType;
  track: 'b2b' | 'eczema' | 'menopause';
  referenceCode: string;
  occurredAt: string;
  locale: 'en' | 'fr' | 'bilingual';
  province?: string;
  fulfillmentPreference?: 'bulk_studio' | 'direct_homeowner';
  targetDeliveryWindow?: string;
  contact: {
    firmName?: string;
    contactName: string;
    email: string;
    phone?: string;
    partnerRole?: string;
  };
  lineItems: StorefrontInboundLineItem[];
  subtotalCad: number;
  discountCad: number;
  taxBreakdown: {
    tpsCad: number;
    tvqCad: number;
    hstCad: number;
    totalTaxCad: number;
    estimated: boolean;
  };
  totalCad: number;
  coBrandingOptions: string[];
  requestSampleKit: boolean;
  appliedCouponCode?: string;
  sanitizedNotes: string;
  healthNotesRedacted: boolean;
  paymentVerification?: {
    provider: 'stripe';
    paymentIntentId: string;
    verifiedOnStorefrontServer: boolean;
    amountPaidCad: number;
  } | null;
  requestType?: 'quote_request' | 'paid_order';
  client?: {
    companyName?: string;
    contactPerson?: string;
    email?: string;
    phone?: string;
    accountType?: string;
    province?: string;
    city?: string;
  };
  projectDetails?: {
    developmentName?: string;
    addressOrLocation?: string;
    unitCount?: number;
    audienceMode?: 'homeowner' | 'renter';
    scentProfile?: string;
  };
  timeline?: {
    requestedDeliveryDate?: string;
    targetDeliveryWindow?: string;
  };
  payment?: {
    subtotal: number;
    depositAmount: number;
    status: 'unpaid' | 'quote_only' | 'deposit_paid' | 'paid_verified';
    paymentIntentId?: string;
    verifiedOnServer?: boolean;
  };
}

export interface StorefrontValidationResult {
  valid: boolean;
  error?: string;
  issues?: string[];
  event?: StorefrontInboundEvent;
}

const MAX_REPLAY_SKEW_SECONDS = 300; // +/- 5 minutes

/**
 * Signs a raw JSON payload using `<timestamp>.<rawBody>` so every webhook carries replay protection.
 */
export function signTimestampedPayload(
  rawBody: string | Buffer,
  secret: string,
  timestampSec: number = Math.floor(Date.now() / 1000),
): { timestamp: string; signature: string } {
  const ts = String(Math.floor(timestampSec));
  const bodyStr = Buffer.isBuffer(rawBody) ? rawBody.toString('utf8') : rawBody;
  const canonical = `${ts}.${bodyStr}`;
  return {
    timestamp: ts,
    signature: computeHmacSha256Signature(canonical, secret),
  };
}

/**
 * Verifies `X-Bridge-Timestamp` (+/- 5 min) + `X-Bridge-Signature: sha256=<hex>` over `<ts>.<rawBody>`.
 */
export function verifyTimestampedHmacSignature(params: {
  rawBody: string | Buffer;
  signatureHeader?: string;
  timestampHeader?: string;
  secret: string;
  maxSkewSeconds?: number;
  nowMs?: number;
}): { ok: boolean; reason?: string } {
  const {
    rawBody,
    signatureHeader,
    timestampHeader,
    secret,
    maxSkewSeconds = MAX_REPLAY_SKEW_SECONDS,
    nowMs = Date.now(),
  } = params;

  if (!secret) {
    return { ok: false, reason: 'HMAC secret is not configured.' };
  }
  if (!timestampHeader || !timestampHeader.trim()) {
    return { ok: false, reason: 'Missing X-Bridge-Timestamp header for replay protection.' };
  }
  const parsedTs = Number(timestampHeader.trim());
  if (!Number.isFinite(parsedTs) || parsedTs <= 0) {
    return { ok: false, reason: 'Invalid X-Bridge-Timestamp header.' };
  }

  // Accept either epoch seconds (10 digits) or epoch ms (13 digits) safely
  const tsMs = parsedTs > 1e12 ? parsedTs : parsedTs * 1000;
  const tsSecNormalized = Math.floor(tsMs / 1000);
  const skewSeconds = Math.abs(nowMs - tsMs) / 1000;
  if (skewSeconds > maxSkewSeconds) {
    return {
      ok: false,
      reason: `Request timestamp outside +/-${maxSkewSeconds}s replay window.`,
    };
  }

  if (!signatureHeader || !signatureHeader.trim()) {
    return { ok: false, reason: 'Missing X-Bridge-Signature header.' };
  }

  const bodyStr = Buffer.isBuffer(rawBody) ? rawBody.toString('utf8') : rawBody;
  const canonical = `${tsSecNormalized}.${bodyStr}`;
  const valid = verifyHmacSha256Signature(canonical, signatureHeader, secret);

  // Also check raw timestampHeader string verbatim in case sender signed epoch ms directly
  if (!valid && timestampHeader.trim() !== String(tsSecNormalized)) {
    const verbatimCanonical = `${timestampHeader.trim()}.${bodyStr}`;
    if (verifyHmacSha256Signature(verbatimCanonical, signatureHeader, secret)) {
      return { ok: true };
    }
  }

  return valid
    ? { ok: true }
    : { ok: false, reason: 'Invalid X-Bridge-Signature HMAC-SHA256 digest.' };
}

/**
 * Blocks SSRF targets (loopback, link-local, metadata, RFC1918 private IPs, .local/.internal).
 * Permits public https:// origins only (http:// requires non-production ALLOW_INSECURE_LOCAL_BRIDGE_HTTP=true).
 */
export function validateSafeStorefrontUrl(rawUrl: string): {
  valid: boolean;
  normalizedUrl?: string;
  error?: string;
} {
  const trimmed = String(rawUrl || '').trim().replace(/\/+$/, '');
  if (!trimmed) {
    return { valid: false, error: 'Storefront URL is required.' };
  }

  let parsed: URL;
  try {
    parsed = new URL(trimmed);
  } catch {
    return { valid: false, error: 'Invalid Storefront URL format.' };
  }

  const allowInsecureHttp =
    process.env.NODE_ENV !== 'production' &&
    process.env.ALLOW_INSECURE_LOCAL_BRIDGE_HTTP === 'true';

  if (parsed.protocol !== 'https:' && !(allowInsecureHttp && parsed.protocol === 'http:')) {
    return {
      valid: false,
      error: 'Storefront URL must use https:// (cleartext http:// is disabled).',
    };
  }

  const host = parsed.hostname.toLowerCase();
  if (!host) {
    return { valid: false, error: 'Storefront URL hostname is missing.' };
  }

  const blockedHosts = new Set([
    'localhost',
    '127.0.0.1',
    '::1',
    '[::1]',
    '0.0.0.0',
    'metadata.google.internal',
    '169.254.169.254',
  ]);

  if (
    blockedHosts.has(host) ||
    host.endsWith('.local') ||
    host.endsWith('.internal') ||
    host.endsWith('.localhost')
  ) {
    return { valid: false, error: 'Private or loopback Storefront URLs are not permitted.' };
  }

  // Block RFC1918 & link-local IPv4 ranges
  const ipv4Match = host.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
  if (ipv4Match) {
    const [_, aStr, bStr] = ipv4Match;
    const a = Number(aStr);
    const b = Number(bStr);
    if (
      a === 10 ||
      a === 127 ||
      a === 0 ||
      (a === 169 && b === 254) ||
      (a === 172 && b >= 16 && b <= 31) ||
      (a === 192 && b === 168)
    ) {
      return { valid: false, error: 'Private IPv4 Storefront URLs are blocked.' };
    }
  }

  return { valid: true, normalizedUrl: `${parsed.origin}${parsed.pathname === '/' ? '' : parsed.pathname}` };
}

/**
 * Computes Quebec/Canadian tax estimates truthfully in CAD.
 */
export function computeCanadianTaxes(subtotalCad: number, province?: string): {
  tpsCad: number;
  tvqCad: number;
  hstCad: number;
  totalTaxCad: number;
  estimated: boolean;
} {
  const safeSubtotal = Math.max(0, Number(subtotalCad) || 0);
  const prov = (province || '').trim().toUpperCase();
  const round = (v: number) => Number(v.toFixed(2));

  if (prov === 'QC' || prov === 'QUEBEC' || prov === 'QUÉBEC') {
    const tpsCad = round(safeSubtotal * 0.05);
    const tvqCad = round(safeSubtotal * 0.09975);
    return {
      tpsCad,
      tvqCad,
      hstCad: 0,
      totalTaxCad: round(tpsCad + tvqCad),
      estimated: true,
    };
  }

  if (prov === 'ON' || prov === 'ONTARIO') {
    const hstCad = round(safeSubtotal * 0.13);
    return { tpsCad: 0, tvqCad: 0, hstCad, totalTaxCad: hstCad, estimated: true };
  }

  if (['NB', 'NL', 'NS', 'PE'].includes(prov)) {
    const hstCad = round(safeSubtotal * 0.15);
    return { tpsCad: 0, tvqCad: 0, hstCad, totalTaxCad: hstCad, estimated: true };
  }

  // Default Canadian GST 5%
  const tpsCad = round(safeSubtotal * 0.05);
  return { tpsCad, tvqCad: 0, hstCad: 0, totalTaxCad: tpsCad, estimated: true };
}

/**
 * Minimizes sensitive personal health/skin free-text on retail Eczema & Menopause tracks.
 */
export function sanitizeHealthAndInquiryNotes(
  rawText: unknown,
  track: 'b2b' | 'eczema' | 'menopause',
): { sanitizedNotes: string; healthNotesRedacted: boolean } {
  const text = String(rawText || '')
    .replace(/<[^>]*>/g, ' ')
    .replace(/[\u0000-\u001F\u007F]/g, ' ')
    .replace(/\s+/g, ' ')
    .trim();

  if (!text) {
    return { sanitizedNotes: '', healthNotesRedacted: false };
  }

  if (track === 'eczema' || track === 'menopause') {
    return {
      sanitizedNotes:
        '[Health & ritual free-text redacted by PII minimization policy; see structured lineItems only.]',
      healthNotesRedacted: true,
    };
  }

  return {
    sanitizedNotes: text.slice(0, 1200),
    healthNotesRedacted: false,
  };
}

/**
 * Validates incoming Storefront event payloads with strict Staging/Production separation
 * and zero trust on client-asserted "paid" statuses without server payment verification.
 */
export function validateStorefrontInboundEvent(raw: unknown): StorefrontValidationResult {
  const issues: string[] = [];
  if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
    return { valid: false, error: 'Payload must be a JSON object.', issues: ['Payload is not an object'] };
  }

  const obj = raw as Record<string, any>;

  const environment = obj.environment;
  if (environment !== 'staging' && environment !== 'production') {
    issues.push("environment must explicitly be 'staging' or 'production' (never infer from delivery stagingMode).");
  }

  const track = obj.track;
  if (track !== 'b2b' && track !== 'eczema' && track !== 'menopause') {
    issues.push("track must be 'b2b', 'eczema', or 'menopause'.");
  }

  const allowedEventTypes: StorefrontEventType[] = [
    'b2b_inquiry',
    'b2b_sample_request',
    'retail_preorder',
    'retail_paid_order',
    'ping',
  ];
  const inferredEventType: StorefrontEventType | undefined =
    !obj.eventType && (obj.requestType === 'quote_request' || obj.requestType === 'paid_order')
      ? obj.requestType === 'paid_order'
        ? 'retail_paid_order'
        : track === 'b2b'
          ? 'b2b_inquiry'
          : 'retail_preorder'
      : undefined;
  const eventType = (obj.eventType || inferredEventType) as StorefrontEventType;
  if (!allowedEventTypes.includes(eventType)) {
    issues.push(`eventType must be one of: ${allowedEventTypes.join(', ')}.`);
  }

  const idempotencyKey = String(
    obj.idempotencyKey || obj.externalOrderId || obj.emailMessageId || '',
  ).trim();
  if (idempotencyKey.length < 8 || idempotencyKey.length > 128) {
    issues.push('idempotencyKey (or externalOrderId / emailMessageId) must be 8–128 characters.');
  }

  const contactRaw =
    obj.contact && typeof obj.contact === 'object'
      ? obj.contact
      : obj.client && typeof obj.client === 'object'
        ? obj.client
        : {};
  const clientRaw = obj.client && typeof obj.client === 'object' ? obj.client : {};
  const contactName = String(
    contactRaw.contactName || contactRaw.contactPerson || contactRaw.name || clientRaw.contactPerson || '',
  )
    .trim()
    .slice(0, 160);
  const email = String(contactRaw.email || clientRaw.email || '').trim().slice(0, 200);
  if (eventType !== 'ping') {
    if (!contactName) issues.push('contact.contactName is required.');
    if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      issues.push('contact.email must be a valid email address.');
    }
  }

  const rawItems = Array.isArray(obj.lineItems) ? obj.lineItems : [];
  if (eventType !== 'ping' && eventType !== 'b2b_sample_request' && rawItems.length === 0) {
    issues.push('lineItems must contain at least one item for orders or inquiries.');
  }

  const lineItems: StorefrontInboundLineItem[] = rawItems.slice(0, 50).map((item: any, idx: number) => {
    const rawName = String(item?.name || item?.productName || '').trim().slice(0, 200);
    const derivedSlug = rawName
      ? rawName.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 100)
      : '';
    const storefrontSlug = String(item?.storefrontSlug || item?.productId || derivedSlug || '').trim().slice(0, 100);
    const variantKey = String(item?.variantKey || item?.variantLabel || item?.boxEdition || 'default').trim().slice(0, 60);
    const name = rawName || storefrontSlug || `Item ${idx + 1}`;
    const qty = Math.max(1, Math.min(10000, Math.round(Number(item?.qty ?? item?.quantity) || 1)));
    const unitPriceCad = Math.max(0, Number(Number(item?.unitPriceCad ?? item?.unitPrice ?? item?.priceCad ?? 0).toFixed(2)));
    const sku = item?.sku ? String(item.sku).trim().slice(0, 80) : undefined;

    if (!storefrontSlug) {
      issues.push(`lineItems[${idx}].storefrontSlug is required.`);
    }
    return { sku, storefrontSlug, variantKey, name, qty, unitPriceCad };
  });

  const requestedType =
    obj.requestType === 'paid_order' || eventType === 'retail_paid_order'
      ? 'paid_order'
      : 'quote_request';

  if (eventType === 'retail_paid_order' || obj.requestType === 'paid_order') {
    const pv = obj.paymentVerification;
    const payObj = obj.payment;
    const hasVerifiedStripe =
      pv &&
      pv.provider === 'stripe' &&
      pv.verifiedOnStorefrontServer === true &&
      typeof pv.paymentIntentId === 'string' &&
      pv.paymentIntentId.trim().length >= 6 &&
      Number(pv.amountPaidCad) > 0;
    const hasVerifiedPaymentObj =
      payObj &&
      payObj.verifiedOnServer === true &&
      (payObj.status === 'paid_verified' || payObj.status === 'deposit_paid') &&
      (Number(payObj.depositAmount) > 0 || Number(payObj.subtotal) > 0);

    if (!hasVerifiedStripe && !hasVerifiedPaymentObj) {
      issues.push(
        'retail_paid_order requires verified Stripe paymentVerification (verifiedOnStorefrontServer: true, paymentIntentId, positive amountPaidCad).',
      );
    }
  }

  if (issues.length > 0) {
    return {
      valid: false,
      error: issues[0],
      issues,
    };
  }

  const computedSubtotal = Number(
    lineItems.reduce((sum, li) => sum + li.unitPriceCad * li.qty, 0).toFixed(2),
  );
  const subtotalCad =
    Number.isFinite(Number(obj.subtotalCad)) && Number(obj.subtotalCad) >= 0
      ? Number(Number(obj.subtotalCad).toFixed(2))
      : computedSubtotal;
  const discountCad = Math.max(0, Number(Number(obj.discountCad || 0).toFixed(2)));
  const province = obj.province ? String(obj.province).trim().toUpperCase().slice(0, 20) : undefined;
  const taxableBase = Math.max(0, Number((subtotalCad - discountCad).toFixed(2)));
  const taxBreakdown =
    obj.taxBreakdown && typeof obj.taxBreakdown === 'object'
      ? {
          tpsCad: Math.max(0, Number(Number(obj.taxBreakdown.tpsCad || 0).toFixed(2))),
          tvqCad: Math.max(0, Number(Number(obj.taxBreakdown.tvqCad || 0).toFixed(2))),
          hstCad: Math.max(0, Number(Number(obj.taxBreakdown.hstCad || 0).toFixed(2))),
          totalTaxCad: Math.max(0, Number(Number(obj.taxBreakdown.totalTaxCad || 0).toFixed(2))),
          estimated: Boolean(obj.taxBreakdown.estimated ?? true),
        }
      : computeCanadianTaxes(taxableBase, province);

  const totalCad =
    Number.isFinite(Number(obj.totalCad)) && Number(obj.totalCad) >= 0
      ? Number(Number(obj.totalCad).toFixed(2))
      : Number((taxableBase + taxBreakdown.totalTaxCad).toFixed(2));

  const { sanitizedNotes, healthNotesRedacted } = sanitizeHealthAndInquiryNotes(
    obj.notes ?? obj.sanitizedNotes,
    track,
  );

  const locale: 'en' | 'fr' | 'bilingual' =
    obj.locale === 'fr' || obj.locale === 'bilingual' ? obj.locale : 'en';

  const fulfillmentPreference: 'bulk_studio' | 'direct_homeowner' | undefined =
    obj.fulfillmentPreference === 'bulk_studio' || obj.fulfillmentPreference === 'direct_homeowner'
      ? obj.fulfillmentPreference
      : undefined;

  const requestedDeliveryDate =
    typeof obj.timeline?.requestedDeliveryDate === 'string' && /^\d{4}-\d{2}-\d{2}/.test(obj.timeline.requestedDeliveryDate)
      ? obj.timeline.requestedDeliveryDate.slice(0, 10)
      : undefined;

  const projectDetails =
    obj.projectDetails && typeof obj.projectDetails === 'object'
      ? {
          ...(obj.projectDetails.developmentName ? { developmentName: String(obj.projectDetails.developmentName).trim().slice(0, 160) } : {}),
          ...(obj.projectDetails.addressOrLocation ? { addressOrLocation: String(obj.projectDetails.addressOrLocation).trim().slice(0, 200) } : {}),
          ...(Number(obj.projectDetails.unitCount) > 0 ? { unitCount: Math.round(Number(obj.projectDetails.unitCount)) } : {}),
          ...(obj.projectDetails.audienceMode === 'homeowner' || obj.projectDetails.audienceMode === 'renter'
            ? { audienceMode: obj.projectDetails.audienceMode }
            : {}),
          ...(obj.projectDetails.scentProfile ? { scentProfile: String(obj.projectDetails.scentProfile).trim().slice(0, 160) } : {}),
        }
      : undefined;

  const event: StorefrontInboundEvent = {
    schemaVersion: 'ljw-storefront-v1',
    idempotencyKey,
    environment,
    eventType,
    track,
    referenceCode: String(obj.referenceCode || `LJW-${idempotencyKey.slice(0, 8).toUpperCase()}`)
      .trim()
      .slice(0, 80),
    occurredAt:
      typeof obj.occurredAt === 'string' && !Number.isNaN(Date.parse(obj.occurredAt))
        ? obj.occurredAt
        : new Date().toISOString(),
    locale,
    ...(province ? { province } : {}),
    ...(fulfillmentPreference ? { fulfillmentPreference } : {}),
    ...(obj.targetDeliveryWindow
      ? { targetDeliveryWindow: String(obj.targetDeliveryWindow).trim().slice(0, 80) }
      : {}),
    contact: {
      ...(contactRaw.firmName || clientRaw.companyName
        ? { firmName: String(contactRaw.firmName || clientRaw.companyName).trim().slice(0, 200) }
        : {}),
      contactName: contactName || 'Ping Check',
      email: email || 'system@ljwellness.net',
      ...(contactRaw.phone || clientRaw.phone
        ? { phone: String(contactRaw.phone || clientRaw.phone).trim().slice(0, 60) }
        : {}),
      ...(contactRaw.partnerRole || clientRaw.accountType
        ? { partnerRole: String(contactRaw.partnerRole || clientRaw.accountType).trim().slice(0, 80) }
        : {}),
    },
    lineItems,
    subtotalCad,
    discountCad,
    taxBreakdown,
    totalCad,
    coBrandingOptions: Array.isArray(obj.coBrandingOptions)
      ? obj.coBrandingOptions.slice(0, 10).map((s: unknown) => String(s).trim().slice(0, 80))
      : [],
    requestSampleKit: Boolean(obj.requestSampleKit),
    ...(obj.appliedCouponCode
      ? { appliedCouponCode: String(obj.appliedCouponCode).trim().slice(0, 40) }
      : {}),
    sanitizedNotes,
    healthNotesRedacted,
    paymentVerification: obj.paymentVerification
      ? {
          provider: 'stripe',
          paymentIntentId: String(obj.paymentVerification.paymentIntentId).trim().slice(0, 120),
          verifiedOnStorefrontServer: Boolean(obj.paymentVerification.verifiedOnStorefrontServer),
          amountPaidCad: Number(Number(obj.paymentVerification.amountPaidCad).toFixed(2)),
        }
      : null,
    requestType: requestedType,
    client: {
      ...(contactRaw.firmName || clientRaw.companyName
        ? { companyName: String(contactRaw.firmName || clientRaw.companyName).trim().slice(0, 200) }
        : {}),
      contactPerson: contactName || 'Ping Check',
      email: email || 'system@ljwellness.net',
      ...(contactRaw.phone || clientRaw.phone
        ? { phone: String(contactRaw.phone || clientRaw.phone).trim().slice(0, 60) }
        : {}),
      ...(contactRaw.partnerRole || clientRaw.accountType
        ? { accountType: String(contactRaw.partnerRole || clientRaw.accountType).trim().slice(0, 80) }
        : {}),
      ...(province || clientRaw.province ? { province: province || String(clientRaw.province).trim().toUpperCase() } : {}),
      ...(clientRaw.city ? { city: String(clientRaw.city).trim().slice(0, 100) } : {}),
    },
    ...(projectDetails ? { projectDetails } : {}),
    timeline: {
      ...(requestedDeliveryDate ? { requestedDeliveryDate } : {}),
      ...(obj.targetDeliveryWindow || obj.timeline?.targetDeliveryWindow
        ? { targetDeliveryWindow: String(obj.timeline?.targetDeliveryWindow || obj.targetDeliveryWindow).trim().slice(0, 80) }
        : {}),
    },
    ...(obj.payment && typeof obj.payment === 'object'
      ? {
          payment: {
            subtotal: Number(Number(obj.payment.subtotal ?? subtotalCad).toFixed(2)),
            depositAmount: Number(Number(obj.payment.depositAmount ?? 0).toFixed(2)),
            status: ['unpaid', 'quote_only', 'deposit_paid', 'paid_verified'].includes(obj.payment.status)
              ? obj.payment.status
              : 'quote_only',
            ...(obj.payment.paymentIntentId ? { paymentIntentId: String(obj.payment.paymentIntentId) } : {}),
            ...(obj.payment.verifiedOnServer !== undefined ? { verifiedOnServer: Boolean(obj.payment.verifiedOnServer) } : {}),
          },
        }
      : {}),
  };

  return { valid: true, event };
}

/**
 * Converts a validated StorefrontInboundEvent into an IncomingOrderQuote operational dossier record.
 */
export function inboundEventToIncomingOrderQuote(
  event: StorefrontInboundEvent,
  docId: string,
): IncomingOrderQuote & { coBrandingOptions?: string[]; discountCad?: number } {
  const isPaid =
    event.eventType === 'retail_paid_order' ||
    (event.requestType === 'paid_order' && Boolean(event.paymentVerification?.verifiedOnStorefrontServer || event.payment?.verifiedOnServer));
  const requestType: 'quote_request' | 'paid_order' = isPaid ? 'paid_order' : 'quote_request';

  const accountType =
    event.client?.accountType ||
    event.contact.partnerRole ||
    (event.track === 'b2b' ? 'Luxury Builder' : 'Retail');

  return {
    id: docId,
    idempotencyKey: event.idempotencyKey,
    source: 'storefront',
    environment: event.environment,
    requestType,
    status: event.environment === 'staging' ? 'sandbox_isolated' : 'pending_review',
    referenceCode: event.referenceCode,
    receivedAt: event.occurredAt || new Date().toISOString(),
    locale: event.locale,
    ...(event.province || event.client?.province ? { province: event.province || event.client?.province } : {}),
    client: {
      companyName: event.client?.companyName || event.contact.firmName || event.contact.contactName,
      contactPerson: event.client?.contactPerson || event.contact.contactName,
      email: event.client?.email || event.contact.email,
      ...(event.client?.phone || event.contact.phone ? { phone: event.client?.phone || event.contact.phone } : {}),
      accountType,
      ...(event.province || event.client?.province ? { province: event.province || event.client?.province } : {}),
      ...(event.client?.city ? { city: event.client.city } : {}),
    },
    lineItems: event.lineItems.map((li) => ({
      sku: li.sku || li.storefrontSlug.toUpperCase(),
      productName: li.name,
      storefrontSlug: li.storefrontSlug,
      variantKey: li.variantKey,
      boxEdition:
        event.fulfillmentPreference === 'bulk_studio'
          ? 'Uniform Development QR'
          : li.variantKey === 'default'
            ? 'Builder Wholesale Run'
            : li.variantKey,
      quantity: li.qty,
      unitPrice: li.unitPriceCad,
    })),
    ...(event.projectDetails ? { projectDetails: event.projectDetails } : {}),
    ...(event.timeline ? { timeline: event.timeline } : {}),
    payment: {
      subtotal: event.subtotalCad,
      depositAmount: event.payment?.depositAmount ?? (event.paymentVerification?.amountPaidCad ?? 0),
      total: event.totalCad,
      status: isPaid
        ? 'paid_verified'
        : event.eventType === 'retail_preorder'
          ? 'unpaid'
          : 'quote_only',
      ...(event.paymentVerification?.paymentIntentId
        ? { paymentIntentId: event.paymentVerification.paymentIntentId }
        : {}),
      verifiedOnServer: Boolean(event.paymentVerification?.verifiedOnStorefrontServer || event.payment?.verifiedOnServer),
    },
    ...(event.sanitizedNotes ? { notes: event.sanitizedNotes } : {}),
    coBrandingOptions: event.coBrandingOptions,
    discountCad: event.discountCad,
  };
}

/**
 * Reconciled default catalog aligning ljwellness-vs3 Storefront slugs with canonical StudioOS SKUs.
 * B2B is positioned as the flagship storefront face, while supporting multi-product Eczema & Menopause tracks.
 * Truthful launch posture: zero fake in-stock inventory until owner toggles real finished batches.
 */
export function buildDefaultAgreementCatalog(): StorefrontAgreementCatalog {
  return {
    schemaVersion: '1.0.0',
    catalogVersion: 1,
    updatedAt: new Date().toISOString(),
    brandPositioning: {
      primaryFace: 'b2b',
      secondaryTracks: ['eczema', 'menopause'],
      currency: 'CAD',
      b2bPriorityNote:
        'B2B Luxury Builders, Architects & Developers remain the primary storefront flagship. Eczema & Menopause lines scale as curated multi-product botanical collections.',
      taxMode: 'estimated_canadian_provincial',
    },
    products: [
      // === B2B FLAGSHIP CLOSING KITS ===
      {
        sku: 'LJW-B2B-RES-01',
        storefrontSlug: 'residence-welcome',
        variantKey: 'default',
        track: 'b2b',
        kind: 'kit',
        nameEn: '01. The Residence Welcome',
        nameFr: '01. Coffret Accueil Résidence',
        formatLabel: '4-pc Architect Box (8 oz candle + 6-cube melts + 50 ml balm + purity card)',
        priceCad: 98,
        status: 'preorder',
        stockAvailable: 0,
        cureLeadDays: 10,
        cureReadyDate: null,
        moq: 5,
        unitCogsCad: 34,
        deductsMaterials: true,
        activeOnStorefront: true,
      },
      {
        sku: 'LJW-B2B-ARC-02',
        storefrontSlug: 'architectural-sanctuary',
        variantKey: 'default',
        track: 'b2b',
        kind: 'kit',
        nameEn: '02. The Architectural Sanctuary',
        nameFr: '02. Coffret Sanctuaire Architectural',
        formatLabel: '5-pc Box (12 oz + 6 oz candles + oval tray + 12-cube melts + 100 ml balm + dossier)',
        priceCad: 165,
        status: 'preorder',
        stockAvailable: 0,
        cureLeadDays: 14,
        cureReadyDate: null,
        moq: 5,
        unitCogsCad: 54,
        deductsMaterials: true,
        activeOnStorefront: true,
      },
      {
        sku: 'LJW-B2B-BES-03',
        storefrontSlug: 'bespoke-estate',
        variantKey: 'default',
        track: 'b2b',
        kind: 'kit',
        nameEn: '03. The Bespoke Estate Box',
        nameFr: '03. Malle Domaine Sur Mesure',
        formatLabel: 'Multi-pc Trunk (3 candles + fluted tray/coasters + warmer + 18-cube melts + hand set)',
        priceCad: 245,
        status: 'preorder',
        stockAvailable: 0,
        cureLeadDays: 21,
        cureReadyDate: null,
        moq: 5,
        unitCogsCad: 82,
        deductsMaterials: true,
        activeOnStorefront: true,
      },
      {
        sku: 'LJW-B2B-SMP-00',
        storefrontSlug: 'studio-material-sample-box',
        variantKey: 'default',
        track: 'b2b',
        kind: 'sample',
        nameEn: 'Paid Studio Material Sample Box',
        nameFr: 'Coffret Échantillon Matériaux Atelier',
        formatLabel: 'Jesmonite disc + unscented votive + 600gsm card swatch + barrier balm ($55 credited @ 10+)',
        priceCad: 55,
        status: 'sample_only',
        stockAvailable: 0,
        cureLeadDays: 7,
        cureReadyDate: null,
        moq: 1,
        unitCogsCad: 19,
        deductsMaterials: true,
        activeOnStorefront: true,
      },
      // === B2B CO-BRANDING ADD-ONS ===
      {
        sku: 'LJW-B2B-ADD-LINEN',
        storefrontSlug: 'monogram-linen-band',
        variantKey: 'per-box',
        track: 'b2b',
        kind: 'addon',
        nameEn: 'Monogrammed Linen Belly Band',
        nameFr: 'Bandeau de Lin Monogrammé',
        formatLabel: 'Per-box architectural linen belly band (+$6/box)',
        priceCad: 6,
        status: 'preorder',
        stockAvailable: 0,
        cureLeadDays: 7,
        cureReadyDate: null,
        moq: 5,
        unitCogsCad: 1.8,
        deductsMaterials: true,
        activeOnStorefront: true,
      },
      {
        sku: 'LJW-B2B-ADD-CARD',
        storefrontSlug: 'embossed-arch-card',
        variantKey: 'per-box',
        track: 'b2b',
        kind: 'addon',
        nameEn: 'Embossed Architectural Welcome Card',
        nameFr: 'Carte d’Accueil Architecturale Embossée',
        formatLabel: '600gsm embossed developer/architect card (+$4/box)',
        priceCad: 4,
        status: 'preorder',
        stockAvailable: 0,
        cureLeadDays: 7,
        cureReadyDate: null,
        moq: 5,
        unitCogsCad: 1.25,
        deductsMaterials: true,
        activeOnStorefront: true,
      },
      {
        sku: 'LJW-B2B-ADD-COLOR',
        storefrontSlug: 'jesmonite-color-match',
        variantKey: 'per-box',
        track: 'b2b',
        kind: 'addon',
        nameEn: 'Jesmonite Vessel Color Match',
        nameFr: 'Teinte Jesmonite Sur Mesure',
        formatLabel: 'Custom mineral pigment match (+$12/box, $95 setup, MOQ 10)',
        priceCad: 12,
        status: 'preorder',
        stockAvailable: 0,
        cureLeadDays: 21,
        cureReadyDate: null,
        moq: 10,
        unitCogsCad: 4.5,
        deductsMaterials: true,
        activeOnStorefront: true,
      },
      {
        sku: 'LJW-B2B-ADD-DOSSIER',
        storefrontSlug: 'custom-estate-insert',
        variantKey: 'per-box',
        track: 'b2b',
        kind: 'addon',
        nameEn: 'Custom Residence Care Dossier',
        nameFr: 'Dossier d’Entretien Résidence Personnalisé',
        formatLabel: 'Printed home finish care insert & QR sheet (+$5/box)',
        priceCad: 5,
        status: 'preorder',
        stockAvailable: 0,
        cureLeadDays: 10,
        cureReadyDate: null,
        moq: 5,
        unitCogsCad: 1.75,
        deductsMaterials: true,
        activeOnStorefront: true,
      },
      {
        sku: 'LJW-B2B-ADD-WHITEGLOVE',
        storefrontSlug: 'priority-white-glove',
        variantKey: 'per-box',
        track: 'b2b',
        kind: 'addon',
        nameEn: 'Priority Closing-Date Staging',
        nameFr: 'Coordination Prioritaire Date de Remise',
        formatLabel: 'Scheduled handover staging per closing date (+$9/box)',
        priceCad: 9,
        status: 'preorder',
        stockAvailable: 0,
        cureLeadDays: 5,
        cureReadyDate: null,
        moq: 5,
        unitCogsCad: 3,
        deductsMaterials: false,
        activeOnStorefront: true,
      },

      // === ECZEMA / SENSITIVE SKIN MULTI-PRODUCT LINE ===
      {
        sku: 'LJW-ECZ-BALM-050',
        storefrontSlug: 'oat-borage-barrier-balm',
        variantKey: '50ml',
        track: 'eczema',
        kind: 'product',
        nameEn: 'Colloidal Oat & Borage Flare Barrier Balm (50 ml)',
        nameFr: 'Baume Barrière Avoine Colloïdale & Bourrache (50 ml)',
        formatLabel: '50 ml Travel / Patch-Test Jar',
        priceCad: 28,
        status: 'preorder',
        stockAvailable: 0,
        cureLeadDays: 7,
        cureReadyDate: null,
        moq: 1,
        unitCogsCad: 7.5,
        deductsMaterials: true,
        activeOnStorefront: true,
      },
      {
        sku: 'LJW-ECZ-BALM-100',
        storefrontSlug: 'oat-borage-barrier-balm',
        variantKey: '100ml',
        track: 'eczema',
        kind: 'product',
        nameEn: 'Colloidal Oat & Borage Flare Barrier Balm (100 ml)',
        nameFr: 'Baume Barrière Avoine Colloïdale & Bourrache (100 ml)',
        formatLabel: '100 ml Full Studio Jar',
        priceCad: 48,
        status: 'preorder',
        stockAvailable: 0,
        cureLeadDays: 7,
        cureReadyDate: null,
        moq: 1,
        unitCogsCad: 12.2,
        deductsMaterials: true,
        activeOnStorefront: true,
      },
      {
        sku: 'LJW-ECZ-BALM-200',
        storefrontSlug: 'oat-borage-barrier-balm',
        variantKey: '200ml',
        track: 'eczema',
        kind: 'product',
        nameEn: 'Colloidal Oat & Borage Flare Barrier Balm (200 ml)',
        nameFr: 'Baume Barrière Avoine Colloïdale & Bourrache (200 ml)',
        formatLabel: '200 ml Family Refill Jar',
        priceCad: 82,
        status: 'preorder',
        stockAvailable: 0,
        cureLeadDays: 7,
        cureReadyDate: null,
        moq: 1,
        unitCogsCad: 20.5,
        deductsMaterials: true,
        activeOnStorefront: true,
      },
      {
        sku: 'LJW-ECZ-WASH-250',
        storefrontSlug: 'amino-lipid-gentle-wash',
        variantKey: '250ml',
        track: 'eczema',
        kind: 'product',
        nameEn: 'Fragrance-Free Oat Amino Calm Wash (250 ml)',
        nameFr: 'Nettoyant Doux Avoine & Acides Aminés Sans Parfum (250 ml)',
        formatLabel: '250 ml Amber Glass Pump',
        priceCad: 34,
        status: 'preorder',
        stockAvailable: 0,
        cureLeadDays: 7,
        cureReadyDate: null,
        moq: 1,
        unitCogsCad: 9.2,
        deductsMaterials: true,
        activeOnStorefront: true,
      },
      {
        sku: 'LJW-ECZ-WASH-500',
        storefrontSlug: 'amino-lipid-gentle-wash',
        variantKey: '500ml',
        track: 'eczema',
        kind: 'product',
        nameEn: 'Fragrance-Free Oat Amino Calm Wash (500 ml)',
        nameFr: 'Nettoyant Doux Avoine & Acides Aminés Sans Parfum (500 ml)',
        formatLabel: '500 ml Studio Refill Bottle',
        priceCad: 58,
        status: 'preorder',
        stockAvailable: 0,
        cureLeadDays: 7,
        cureReadyDate: null,
        moq: 1,
        unitCogsCad: 15.8,
        deductsMaterials: true,
        activeOnStorefront: true,
      },
      {
        sku: 'LJW-ECZ-STICK-01',
        storefrontSlug: 'pocket-crease-flare-stick',
        variantKey: 'single',
        track: 'eczema',
        kind: 'product',
        nameEn: 'Pocket Hand & Crease Shield Stick (Single)',
        nameFr: 'Bâton Protecteur Mains & Plis Cutanés (Unité)',
        formatLabel: 'Single 30 g Pocket Stick',
        priceCad: 26,
        status: 'preorder',
        stockAvailable: 0,
        cureLeadDays: 5,
        cureReadyDate: null,
        moq: 1,
        unitCogsCad: 6.4,
        deductsMaterials: true,
        activeOnStorefront: true,
      },
      {
        sku: 'LJW-ECZ-STICK-02',
        storefrontSlug: 'pocket-crease-flare-stick',
        variantKey: 'duo',
        track: 'eczema',
        kind: 'product',
        nameEn: 'Pocket Hand & Crease Shield Stick (2-Pack Duo)',
        nameFr: 'Bâton Protecteur Mains & Plis Cutanés (Duo)',
        formatLabel: '2-Pack Desk & Bag Duo',
        priceCad: 46,
        status: 'preorder',
        stockAvailable: 0,
        cureLeadDays: 5,
        cureReadyDate: null,
        moq: 1,
        unitCogsCad: 12.1,
        deductsMaterials: true,
        activeOnStorefront: true,
      },
      {
        sku: 'LJW-ECZ-MIST-100',
        storefrontSlug: 'microbiome-recovery-mist',
        variantKey: '100ml-waitlist',
        track: 'eczema',
        kind: 'product',
        nameEn: 'Post-Flare Colloidal Hydro-Calm Mist',
        nameFr: 'Brume Apaisante Post-Crise Avoine Colloïdale',
        formatLabel: '100 ml First-Batch Reservation',
        priceCad: 36,
        status: 'in_development',
        stockAvailable: 0,
        cureLeadDays: 14,
        cureReadyDate: null,
        moq: 1,
        unitCogsCad: 8.8,
        deductsMaterials: true,
        activeOnStorefront: true,
      },
      {
        sku: 'LJW-ECZ-SOAK-400',
        storefrontSlug: 'unscented-bath-soak',
        variantKey: '400g-waitlist',
        track: 'eczema',
        kind: 'product',
        nameEn: 'Silky Colloidal Oat & Marshmallow Bath Soak',
        nameFr: 'Bain Apaisant Avoine Colloïdale & Guimauve',
        formatLabel: '400 g Pouch First-Batch Reservation',
        priceCad: 32,
        status: 'in_development',
        stockAvailable: 0,
        cureLeadDays: 7,
        cureReadyDate: null,
        moq: 1,
        unitCogsCad: 7.4,
        deductsMaterials: true,
        activeOnStorefront: true,
      },
      {
        sku: 'LJW-ECZ-MELT-12',
        storefrontSlug: 'home-air-safe-melt-set',
        variantKey: '12-cube-waitlist',
        track: 'eczema',
        kind: 'product',
        nameEn: 'Sanctuary Bedroom Unscented Botanical Melts',
        nameFr: 'Fondants Botaniques Sans Parfum Chambre Sanctuaire',
        formatLabel: '12-cube set',
        priceCad: 28,
        status: 'in_development',
        stockAvailable: 0,
        cureLeadDays: 10,
        cureReadyDate: null,
        moq: 1,
        unitCogsCad: 6.9,
        deductsMaterials: true,
        activeOnStorefront: true,
      },
      {
        sku: 'LJW-ECZ-BND-TRIO',
        storefrontSlug: 'calm-barrier-trio',
        variantKey: 'bundle',
        track: 'eczema',
        kind: 'bundle',
        nameEn: 'The Complete Calm Barrier Trio',
        nameFr: 'Trio Barrière Apaisante Complet',
        formatLabel: '250 ml wash + 100 ml balm + 30 g stick',
        priceCad: 96,
        status: 'preorder',
        stockAvailable: 0,
        cureLeadDays: 7,
        cureReadyDate: null,
        moq: 1,
        unitCogsCad: 27.8,
        deductsMaterials: true,
        activeOnStorefront: true,
      },
      {
        sku: 'LJW-ECZ-BND-DAILY',
        storefrontSlug: 'daily-reactive-cleanse',
        variantKey: 'bundle',
        track: 'eczema',
        kind: 'bundle',
        nameEn: 'Daily Reactive Wash & Balm Pair',
        nameFr: 'Duo Quotidien Peau Réactive',
        formatLabel: '250 ml wash + 100 ml balm',
        priceCad: 74,
        status: 'preorder',
        stockAvailable: 0,
        cureLeadDays: 7,
        cureReadyDate: null,
        moq: 1,
        unitCogsCad: 21.4,
        deductsMaterials: true,
        activeOnStorefront: true,
      },
      {
        sku: 'LJW-ECZ-BND-TRAVEL',
        storefrontSlug: 'travel-flare-shield',
        variantKey: 'bundle',
        track: 'eczema',
        kind: 'bundle',
        nameEn: 'Pocket Flare Shield & Mini Balm Duo',
        nameFr: 'Duo Nomade Bouclier & Mini Baume',
        formatLabel: '30 g stick + 50 ml balm',
        priceCad: 48,
        status: 'preorder',
        stockAvailable: 0,
        cureLeadDays: 7,
        cureReadyDate: null,
        moq: 1,
        unitCogsCad: 13.9,
        deductsMaterials: true,
        activeOnStorefront: true,
      },

      // === MENOPAUSE / SAY IT PLAIN MULTI-PRODUCT LINE ===
      {
        sku: 'LJW-MEN-MIST-100',
        storefrontSlug: 'peri-cooling-mist',
        variantKey: '100ml',
        track: 'menopause',
        kind: 'product',
        nameEn: 'Thermal Calm Mineral Facial & Neck Mist',
        nameFr: 'Brume Minérale Rafraîchissante Visage & Cou',
        formatLabel: '100 ml (Sync Say It Plain price)',
        priceCad: 0,
        status: 'in_development',
        stockAvailable: 0,
        cureLeadDays: 14,
        cureReadyDate: null,
        moq: 1,
        unitCogsCad: 0,
        deductsMaterials: true,
        activeOnStorefront: true,
      },
      {
        sku: 'LJW-MEN-CAND-10Z',
        storefrontSlug: 'peri-night-candle',
        variantKey: '10oz',
        track: 'menopause',
        kind: 'product',
        nameEn: 'Restorative Dusk Unscented Jesmonite Candle',
        nameFr: 'Bougie Réparatrice Crépuscule Jesmonite Sans Parfum',
        formatLabel: '10 oz Jesmonite vessel',
        priceCad: 0,
        status: 'in_development',
        stockAvailable: 0,
        cureLeadDays: 14,
        cureReadyDate: null,
        moq: 1,
        unitCogsCad: 0,
        deductsMaterials: true,
        activeOnStorefront: true,
      },
      {
        sku: 'LJW-MEN-BALM-150',
        storefrontSlug: 'meno-night-balm',
        variantKey: '150ml',
        track: 'menopause',
        kind: 'product',
        nameEn: 'Deep Moisture Lipid Renewal Body Butter',
        nameFr: 'Beurre Corporel Renouvellement Lipidique Intense',
        formatLabel: '150 ml rich butter jar',
        priceCad: 0,
        status: 'in_development',
        stockAvailable: 0,
        cureLeadDays: 14,
        cureReadyDate: null,
        moq: 1,
        unitCogsCad: 0,
        deductsMaterials: true,
        activeOnStorefront: true,
      },
      {
        sku: 'LJW-MEN-MELT-12',
        storefrontSlug: 'meno-wax-melts',
        variantKey: '12-cube',
        track: 'menopause',
        kind: 'product',
        nameEn: 'Sanctuary Unscented Clean Wax Melts',
        nameFr: 'Fondants Purs Sans Parfum Sanctuaire',
        formatLabel: '12-cube set',
        priceCad: 0,
        status: 'in_development',
        stockAvailable: 0,
        cureLeadDays: 10,
        cureReadyDate: null,
        moq: 1,
        unitCogsCad: 0,
        deductsMaterials: true,
        activeOnStorefront: true,
      },
      {
        sku: 'LJW-MEN-ELIX-050',
        storefrontSlug: 'post-barrier-elixir',
        variantKey: '50ml',
        track: 'menopause',
        kind: 'product',
        nameEn: 'Cellular Radiance Unscented Facial Elixir',
        nameFr: 'Élixir Facial Éclat Cellulaire Sans Parfum',
        formatLabel: '50 ml botanical facial oil',
        priceCad: 0,
        status: 'in_development',
        stockAvailable: 0,
        cureLeadDays: 14,
        cureReadyDate: null,
        moq: 1,
        unitCogsCad: 0,
        deductsMaterials: true,
        activeOnStorefront: true,
      },
      {
        sku: 'LJW-MEN-DUO-01',
        storefrontSlug: 'post-hearth-duo',
        variantKey: 'duo',
        track: 'menopause',
        kind: 'bundle',
        nameEn: 'Morning Stillness Vessel & Hand Ritual',
        nameFr: 'Rituel Matinal Bougeoir & Soin des Mains',
        formatLabel: 'Jesmonite candle + 100 ml hand balm',
        priceCad: 0,
        status: 'in_development',
        stockAvailable: 0,
        cureLeadDays: 14,
        cureReadyDate: null,
        moq: 1,
        unitCogsCad: 0,
        deductsMaterials: true,
        activeOnStorefront: true,
      },
    ],
  };
}

/**
 * Validates and normalizes an updated agreement catalog saved from StudioOS UI.
 */
export function normalizeAgreementCatalogInput(raw: unknown): {
  valid: boolean;
  catalog?: StorefrontAgreementCatalog;
  error?: string;
} {
  if (!raw || typeof raw !== 'object') {
    return { valid: false, error: 'Catalog payload must be an object.' };
  }
  const obj = raw as Record<string, any>;
  if (!Array.isArray(obj.products)) {
    return { valid: false, error: 'Catalog products array is required.' };
  }

  const allowedTracks: StorefrontTrack[] = ['b2b', 'eczema', 'menopause', 'purity'];
  const allowedKinds: StorefrontSkuKind[] = ['kit', 'addon', 'sample', 'product', 'bundle'];
  const allowedStatuses: StorefrontAvailabilityStatus[] = [
    'preorder',
    'sample_only',
    'in_development',
    'in_stock',
    'sold_out',
  ];

  const seenSkus = new Set<string>();
  const normalizedProducts: AgreedCatalogSku[] = [];

  for (let i = 0; i < obj.products.length; i += 1) {
    const item = obj.products[i] || {};
    const sku = String(item.sku || '').trim().toUpperCase().slice(0, 64);
    const storefrontSlug = String(item.storefrontSlug || '').trim().toLowerCase().slice(0, 100);
    const variantKey = String(item.variantKey || 'default').trim().slice(0, 60);

    if (!sku || !/^[A-Z0-9_-]{3,64}$/.test(sku)) {
      return { valid: false, error: `Row ${i + 1}: SKU must be 3-64 alphanumeric/hyphen/underscore chars.` };
    }
    if (seenSkus.has(sku)) {
      return { valid: false, error: `Duplicate SKU detected: ${sku}` };
    }
    seenSkus.add(sku);

    if (!storefrontSlug || !/^[a-z0-9_-]{2,100}$/.test(storefrontSlug)) {
      return { valid: false, error: `SKU ${sku}: storefrontSlug must be lowercase alphanumeric/hyphen.` };
    }

    const track: StorefrontTrack = allowedTracks.includes(item.track) ? item.track : 'b2b';
    const kind: StorefrontSkuKind = allowedKinds.includes(item.kind) ? item.kind : 'product';
    const status: StorefrontAvailabilityStatus = allowedStatuses.includes(item.status)
      ? item.status
      : 'in_development';

    normalizedProducts.push({
      sku,
      storefrontSlug,
      variantKey,
      track,
      kind,
      nameEn: String(item.nameEn || sku).trim().slice(0, 200),
      nameFr: String(item.nameFr || item.nameEn || sku).trim().slice(0, 200),
      formatLabel: String(item.formatLabel || '').trim().slice(0, 240),
      priceCad: Math.max(0, Number(Number(item.priceCad || 0).toFixed(2))),
      status,
      stockAvailable: Math.max(0, Math.round(Number(item.stockAvailable) || 0)),
      cureLeadDays: Math.max(0, Math.min(365, Math.round(Number(item.cureLeadDays) || 0))),
      cureReadyDate: item.cureReadyDate ? String(item.cureReadyDate).trim().slice(0, 40) : null,
      moq: Math.max(1, Math.min(10000, Math.round(Number(item.moq) || 1))),
      unitCogsCad: Math.max(0, Number(Number(item.unitCogsCad || 0).toFixed(2))),
      deductsMaterials: Boolean(item.deductsMaterials ?? true),
      activeOnStorefront: Boolean(item.activeOnStorefront ?? true),
    });
  }

  const prevVersion = Math.max(1, Math.round(Number(obj.catalogVersion) || 1));

  return {
    valid: true,
    catalog: {
      schemaVersion: '1.0.0',
      catalogVersion: prevVersion,
      updatedAt: new Date().toISOString(),
      brandPositioning: {
        primaryFace: 'b2b',
        secondaryTracks: ['eczema', 'menopause'],
        currency: 'CAD',
        b2bPriorityNote:
          String(
            obj.brandPositioning?.b2bPriorityNote ||
              'B2B Luxury Builders, Architects & Developers remain the primary storefront flagship. Eczema & Menopause lines scale as curated multi-product botanical collections.',
          ).slice(0, 500),
        taxMode: 'estimated_canadian_provincial',
      },
      products: normalizedProducts,
    },
  };
}
