import { describe, it, expect } from 'vitest';
import {
  buildDefaultAgreementCatalog,
  computeCanadianTaxes,
  normalizeAgreementCatalogInput,
  sanitizeHealthAndInquiryNotes,
  signTimestampedPayload,
  validateSafeStorefrontUrl,
  validateStorefrontInboundEvent,
  verifyTimestampedHmacSignature,
} from '../storefrontBridge';

describe('storefrontBridge security & schema', () => {
  it('signs and verifies HMAC-SHA256 with +/-5m timestamp replay protection', () => {
    const secret = 'test-storefront-hmac-secret-32chars';
    const rawBody = JSON.stringify({ hello: 'ljwellness' });
    const nowSec = 1760000000;
    const { timestamp, signature } = signTimestampedPayload(rawBody, secret, nowSec);

    const ok = verifyTimestampedHmacSignature({
      rawBody,
      timestampHeader: timestamp,
      signatureHeader: signature,
      secret,
      nowMs: nowSec * 1000 + 45_000, // 45s later -> valid
    });
    expect(ok.ok).toBe(true);

    // Replay > 5 minutes rejected
    const stale = verifyTimestampedHmacSignature({
      rawBody,
      timestampHeader: timestamp,
      signatureHeader: signature,
      secret,
      nowMs: nowSec * 1000 + 305_000,
    });
    expect(stale.ok).toBe(false);
    expect(stale.reason).toContain('replay window');

    // Tampered body rejected
    const tampered = verifyTimestampedHmacSignature({
      rawBody: JSON.stringify({ hello: 'tampered' }),
      timestampHeader: timestamp,
      signatureHeader: signature,
      secret,
      nowMs: nowSec * 1000,
    });
    expect(tampered.ok).toBe(false);
  });

  it('blocks SSRF internal/loopback URLs and cleartext http:// while permitting https:// staging.ljwellness.net and ljwellness.net', () => {
    expect(validateSafeStorefrontUrl('https://staging.ljwellness.net').valid).toBe(true);
    expect(validateSafeStorefrontUrl('http://staging.ljwellness.net').valid).toBe(false);
    expect(validateSafeStorefrontUrl('https://ljwellness.net/').normalizedUrl).toBe('https://ljwellness.net');
    expect(validateSafeStorefrontUrl('https://localhost:3000').valid).toBe(false);
    expect(validateSafeStorefrontUrl('http://127.0.0.1:8080').valid).toBe(false);
    expect(validateSafeStorefrontUrl('https://169.254.169.254/latest/meta-data').valid).toBe(false);
    expect(validateSafeStorefrontUrl('https://192.168.1.50').valid).toBe(false);
    expect(validateSafeStorefrontUrl('ftp://ljwellness.net').valid).toBe(false);
  });

  it('redacts sensitive health notes on Eczema and Menopause tracks while keeping B2B project notes', () => {
    const eczemaNote = sanitizeHealthAndInquiryNotes('Severe flare on hands and neck for 3 months', 'eczema');
    expect(eczemaNote.healthNotesRedacted).toBe(true);
    expect(eczemaNote.sanitizedNotes).not.toContain('Severe flare');

    const menoNote = sanitizeHealthAndInquiryNotes('Hot flashes waking me up at 3am', 'menopause');
    expect(menoNote.healthNotesRedacted).toBe(true);
    expect(menoNote.sanitizedNotes).not.toContain('Hot flashes');

    const b2bNote = sanitizeHealthAndInquiryNotes('24 penthouse handovers in November, bilingual inserts', 'b2b');
    expect(b2bNote.healthNotesRedacted).toBe(false);
    expect(b2bNote.sanitizedNotes).toContain('24 penthouse handovers');
  });

  it('calculates truthful Quebec TPS (5%) + TVQ (9.975%) taxes', () => {
    const qc = computeCanadianTaxes(100, 'QC');
    expect(qc.tpsCad).toBe(5);
    expect(qc.tvqCad).toBe(9.98); // 9.975 rounded to cents
    expect(qc.totalTaxCad).toBe(14.98);
    expect(qc.estimated).toBe(true);
  });

  it('rejects unverified retail_paid_order claims and missing staging/production environment flags', () => {
    const missingEnv = validateStorefrontInboundEvent({
      eventType: 'b2b_inquiry',
      track: 'b2b',
      idempotencyKey: 'key_1234567890',
      contact: { contactName: 'Claire', email: 'claire@builder.ca' },
      lineItems: [{ storefrontSlug: 'residence-welcome', qty: 5, unitPriceCad: 98 }],
    });
    expect(missingEnv.valid).toBe(false);

    const fakePaid = validateStorefrontInboundEvent({
      environment: 'production',
      eventType: 'retail_paid_order',
      track: 'eczema',
      idempotencyKey: 'key_paid_fake_01',
      contact: { contactName: 'Sam', email: 'sam@example.com' },
      lineItems: [{ storefrontSlug: 'oat-borage-barrier-balm', variantKey: '100ml', qty: 1, unitPriceCad: 48 }],
      paymentVerification: { provider: 'stripe', paymentIntentId: 'pi_123456', verifiedOnStorefrontServer: false, amountPaidCad: 48 },
    });
    expect(fakePaid.valid).toBe(false);

    const validB2b = validateStorefrontInboundEvent({
      environment: 'staging',
      eventType: 'b2b_inquiry',
      track: 'b2b',
      idempotencyKey: 'key_b2b_staging_01',
      locale: 'bilingual',
      province: 'QC',
      fulfillmentPreference: 'bulk_studio',
      contact: { firmName: 'Groupe Architecture', contactName: 'Luc', email: 'luc@arch.ca' },
      lineItems: [{ storefrontSlug: 'architectural-sanctuary', qty: 10, unitPriceCad: 165 }],
    });
    expect(validB2b.valid).toBe(true);
    expect(validB2b.event?.environment).toBe('staging');
    expect(validB2b.event?.subtotalCad).toBe(1650);
    expect(validB2b.event?.taxBreakdown.totalTaxCad).toBe(247.09);
  });

  it('builds reconciled B2B flagship + multi-product Eczema & Menopause agreement catalog with zero fake in-stock claims', () => {
    const catalog = buildDefaultAgreementCatalog();
    expect(catalog.brandPositioning.primaryFace).toBe('b2b');
    expect(catalog.products.some((p) => p.sku === 'LJW-B2B-RES-01' && p.storefrontSlug === 'residence-welcome')).toBe(true);
    expect(catalog.products.some((p) => p.track === 'eczema' && p.storefrontSlug === 'oat-borage-barrier-balm')).toBe(true);
    expect(catalog.products.some((p) => p.track === 'menopause' && p.storefrontSlug === 'peri-cooling-mist')).toBe(true);
    // Truthful readiness: nothing falsely marked in_stock initially
    expect(catalog.products.every((p) => p.status !== 'in_stock')).toBe(true);

    const renormalized = normalizeAgreementCatalogInput(catalog);
    expect(renormalized.valid).toBe(true);
    expect(renormalized.catalog?.products.length).toBe(catalog.products.length);
  });

  it('normalizes webhook/email parser payloads (client, requestType, projectDetails, timeline, externalOrderId)', async () => {
    const { inboundEventToIncomingOrderQuote } = await import('../storefrontBridge');
    const parsed = validateStorefrontInboundEvent({
      environment: 'staging',
      requestType: 'quote_request',
      track: 'b2b',
      externalOrderId: 'ext_email_msg_8812',
      locale: 'fr',
      province: 'QC',
      client: {
        companyName: 'Développements Saint-Denis',
        contactPerson: 'Marc Gagnon',
        email: 'marc@saintdenis.ca',
        accountType: 'Condo Developer',
        province: 'QC',
        city: 'Montréal',
      },
      projectDetails: {
        developmentName: 'Le Saint-Denis',
        unitCount: 36,
        audienceMode: 'homeowner',
        scentProfile: 'Cedar & Bergamot',
      },
      timeline: {
        requestedDeliveryDate: '2027-01-15',
      },
      lineItems: [
        {
          sku: 'LJW-B2B-ARC-02',
          productName: '02. The Architectural Sanctuary',
          boxEdition: 'Uniform Development QR',
          quantity: 36,
          unitPrice: 165,
        },
      ],
    });

    expect(parsed.valid).toBe(true);
    expect(parsed.event?.idempotencyKey).toBe('ext_email_msg_8812');
    expect(parsed.event?.requestType).toBe('quote_request');
    expect(parsed.event?.projectDetails?.developmentName).toBe('Le Saint-Denis');
    expect(parsed.event?.lineItems[0].qty).toBe(36);

    const incoming = inboundEventToIncomingOrderQuote(parsed.event!, 'storefront');
    expect(incoming.client.companyName).toBe('Développements Saint-Denis');
    expect(incoming.timeline?.requestedDeliveryDate).toBe('2027-01-15');
    expect(incoming.status).toBe('sandbox_isolated');
  });
});
