import { ShoppingFlowService } from './shopping-flow.service';
import { createHash } from 'crypto';
import sharp from 'sharp';
import axios from 'axios';

const token = 'a'.repeat(64);
const cfg = {
  shoppingFlowEnabled: true,
  shoppingFlowId: '123',
  searchFlowId: '456',
  shoppingTermsVersion: 'v1',
  shoppingTermsSummary: 'Terms',
  shoppingTermsUrl: 'https://store.example/terms',
  shoppingPrivacyUrl: 'https://store.example/privacy',
  cardPaymentsEnabled: true,
};
const product = {
  id: 'p1',
  businessId: 'b1',
  name: 'Milk',
  status: 'ACTIVE',
  price: 2,
  currency: 'USD',
  stockStatus: 'instock',
  stockQuantity: 5,
  variants: [],
  imageUrl: null,
  description: 'Categories: Dairy',
};

describe('ShoppingFlowService', () => {
  let db: any, service: ShoppingFlowService, session: any, products: any;
  beforeEach(() => {
    session = {
      id: createHash('sha256').update(token).digest('hex'),
      businessId: 'b1',
      customerId: 'c1',
      phone: '263771234567',
      termsVersion: 'v1',
      expiresAt: new Date(Date.now() + 60_000),
      selectionJson: '{}',
      resultJson: null,
    };
    db = {
      businessIntegration: {
        findFirst: jest
          .fn()
          .mockResolvedValue({ credentialsEncrypted: 'encrypted' }),
      },
      shoppingFlowSession: {
        findUnique: jest.fn(async () => session),
        findUniqueOrThrow: jest.fn(async () => session),
        update: jest.fn(async ({ data }) => Object.assign(session, data)),
        create: jest.fn(),
      },
      shoppingTermsAcceptance: {
        findUnique: jest.fn().mockResolvedValue({ version: 'v1' }),
        upsert: jest.fn(),
      },
      product: { findFirst: jest.fn().mockResolvedValue(product) },
      cart: {
        findFirst: jest
          .fn()
          .mockResolvedValue({ id: 'cart', currency: 'USD', items: [] }),
        update: jest.fn(),
      },
      cartItem: {
        create: jest.fn(),
        update: jest.fn(),
        findMany: jest.fn().mockResolvedValue([{ lineTotal: 4 }]),
      },
      payment: { findFirst: jest.fn() },
      customer: { findFirst: jest.fn().mockResolvedValue({ id: 'c1' }) },
    };
    db.$transaction = jest.fn((callback) => callback(db));
    products = { listProducts: jest.fn().mockResolvedValue([product]) };
    service = new ShoppingFlowService(
      db,
      { decryptJson: () => cfg } as any,
      products,
    );
  });
  const exchange = (
    service: ShoppingFlowService,
    screen: string,
    data: any = {},
  ) =>
    service.exchange({
      action: 'data_exchange',
      flow_token: token,
      screen,
      data,
    });
  it('requires acceptance before allowing direct search or selection', async () => {
    db.shoppingTermsAcceptance.findUnique.mockResolvedValue(null);
    expect((await exchange(service, 'SEARCH')).screen).toBe('TERMS');
    expect(products.listProducts).not.toHaveBeenCalled();
    expect(
      (await exchange(service, 'TERMS', { accepted: 'true' })).screen,
    ).toBe('TERMS');
    await exchange(service, 'TERMS', { accepted: true });
    expect(
      db.shoppingTermsAcceptance.upsert.mock.calls[0][0].create,
    ).toMatchObject({
      businessId: 'b1',
      customerId: 'c1',
      version: 'v1',
      termsUrl: cfg.shoppingTermsUrl,
    });
  });
  it('uses hosted policy links when a merchant enters policy text instead of URLs', async () => {
    const oldOrigin = process.env.PUBLIC_URL;
    process.env.PUBLIC_URL = 'https://api.example.com';
    const textCfg = {
      ...cfg,
      shoppingTermsUrl: '',
      shoppingPrivacyUrl: '',
      shoppingTermsSummary: '',
      shoppingTermsText: 'Shopping terms text',
      shoppingPrivacyText: 'Privacy notice text',
    };
    const serviceWithText = new ShoppingFlowService(
      db,
      { decryptJson: () => textCfg } as any,
      products,
    );
    db.shoppingTermsAcceptance.findUnique.mockResolvedValue(null);
    try {
      const result = await serviceWithText.exchange({
        action: 'INIT',
        flow_token: token,
      });
      expect(result.screen).toBe('TERMS');
      expect(result.data.summary).toBe('Shopping terms text');
      expect(result.data.terms_url).toBe(
        'https://api.example.com/whatsapp/policies/b1/v1/terms',
      );
      expect(result.data.privacy_url).toBe(
        'https://api.example.com/whatsapp/policies/b1/v1/privacy',
      );
    } finally {
      if (oldOrigin === undefined) delete process.env.PUBLIC_URL;
      else process.env.PUBLIC_URL = oldOrigin;
    }
  });
  it('finishes consent back into chat without starting search or adding products', async () => {
    session.selectionJson = JSON.stringify({ mode: 'consent' });
    db.shoppingTermsAcceptance.findUnique.mockResolvedValue(null);
    const result = await exchange(service, 'TERMS', { accepted: true });
    expect(result.screen).toBe('SUCCESS');
    expect(result.data.extension_message_response.params.value).toBe(
      `consent_flow:${token}`,
    );
    expect(JSON.parse(session.resultJson).kind).toBe('consent');
    expect(products.listProducts).not.toHaveBeenCalled();
    expect(db.cartItem.create).not.toHaveBeenCalled();
  });
  it('finishes a search selection back into chat and validates completion ownership', async () => {
    session.selectionJson = JSON.stringify({ mode: 'search' });
    await exchange(service, 'SEARCH', { category: 'all' });
    const result = await exchange(service, 'RESULTS', { product: 'p1' });
    expect(result.screen).toBe('SUCCESS');
    expect(result.data.extension_message_response.params.value).toBe(
      `search_flow:${token}`,
    );
    expect(
      await service.completion('b1', 'c1', session.phone, token, 'search'),
    ).toMatchObject({ productId: 'p1', variantId: null });
    expect(
      await service.completion('other', 'c1', session.phone, token, 'search'),
    ).toBeNull();
    expect(db.cartItem.create).not.toHaveBeenCalled();
  });
  it('launches search directly on SEARCH with its data, without first-screen INIT redirection', async () => {
    const saved = { ...process.env };
    process.env.WHATSAPP_APP_SECRET = 'configured';
    process.env.WHATSAPP_FLOWS_PRIVATE_KEY_PATH = '/mounted/private.pem';
    try {
      const launched = await service.launch(
        'b1',
        'c1',
        session.phone,
        'search',
      );
      const params = launched!.payload.interactive.action.parameters;
      expect(params.flow_id).toBe('456');
      expect(params.flow_action).toBe('navigate');
      expect(params.flow_action_payload?.screen).toBe('SEARCH');
      expect(params.flow_action_payload?.data.categories).toEqual(
        expect.arrayContaining([
          { id: 'all', title: 'All products' },
          { id: 'Dairy', title: 'Dairy' },
        ]),
      );
      expect(
        JSON.parse(
          db.shoppingFlowSession.create.mock.calls[0][0].data.selectionJson,
        ).mode,
      ).toBe('search');
    } finally {
      process.env = saved;
    }
  });
  it('shows featured thumbnails and returns a chosen featured product to chat', async () => {
    session.selectionJson = JSON.stringify({
      mode: 'search',
      visualSearch: true,
    });
    const initial = await service.exchange({
      action: 'INIT',
      flow_token: token,
    });
    expect(initial.data.has_featured).toBe(true);
    expect(initial.data.featured[0]).toMatchObject({
      id: 'p1',
      title: 'Milk',
      description: 'USD 2.00 · In stock',
    });
    expect(initial.data.featured[0].image).toMatch(/^iVBOR/);
    const chosen = await exchange(service, 'SEARCH', {
      category: ['all'],
      query: '',
      featured: 'p1',
    });
    expect(chosen.screen).toBe('SUCCESS');
    expect(chosen.data.extension_message_response.params.value).toBe(
      `search_flow:${token}`,
    );
    expect(db.cartItem.create).not.toHaveBeenCalled();
  });
  it('accepts category chips and returns product thumbnails in search results', async () => {
    session.selectionJson = JSON.stringify({
      mode: 'search',
      visualSearch: true,
    });
    const result = await exchange(service, 'SEARCH', {
      category: ['Dairy'],
      query: 'Milk',
    });
    expect(result.screen).toBe('RESULTS');
    expect(result.data.products[0].image).toMatch(/^iVBOR/);
    expect(
      (await exchange(service, 'SEARCH', { category: ['Other'] })).screen,
    ).toBe('SEARCH');
  });
  it('refreshes only the selected category and permits its product to return to chat', async () => {
    products.listProducts.mockResolvedValue([
      product,
      {
        ...product,
        id: 'p2',
        name: 'Phone',
        description: 'Categories: Phones',
      },
    ]);
    session.selectionJson = JSON.stringify({
      mode: 'search',
      visualSearch: true,
    });
    const response = await exchange(service, 'SEARCH', {
      action: 'category_change',
      category: ['Dairy'],
    });
    expect(response.screen).toBe('SEARCH');
    expect(response.data.selected_categories).toEqual(['Dairy']);
    expect(response.data.featured.map((p) => p.id)).toEqual(['p1']);
    expect(JSON.parse(session.selectionJson).featuredOffered).toEqual(['p1']);
    const selected = await exchange(service, 'SEARCH', {
      category: ['Dairy'],
      featured: 'p1',
    });
    expect(selected.screen).toBe('SUCCESS');
    expect(db.cartItem.create).not.toHaveBeenCalled();
  });
  it('clears displayed products when a category has no available products', async () => {
    session.selectionJson = JSON.stringify({
      mode: 'search',
      visualSearch: true,
    });
    const response = await exchange(service, 'SEARCH', {
      action: 'category_change',
      category: ['Phones'],
    });
    expect(response.data.featured).toEqual([]);
    expect(response.data.has_featured).toBe(false);
    expect(JSON.parse(session.selectionJson).featuredOffered).toEqual([]);
  });
  it('converts approved WebP product images into small JPEG thumbnails', async () => {
    const original = process.env.WHATSAPP_FLOWS_IMAGE_ORIGINS;
    process.env.WHATSAPP_FLOWS_IMAGE_ORIGINS = 'https://cdn.example';
    const bytes = await sharp({
      create: { width: 1000, height: 800, channels: 3, background: '#ff0000' },
    })
      .webp()
      .toBuffer();
    const get = jest.spyOn(axios, 'get').mockResolvedValue({
      data: bytes,
      headers: { 'content-type': 'image/webp' },
    });
    try {
      const image = await (service as any).image(
        'https://cdn.example/product.webp',
      );
      const buffer = Buffer.from(image, 'base64');
      const metadata = await sharp(buffer).metadata();
      expect(metadata.format).toBe('jpeg');
      expect(metadata.width).toBeLessThanOrEqual(240);
      expect(buffer.length).toBeLessThanOrEqual(80000);
    } finally {
      get.mockRestore();
      if (original === undefined)
        delete process.env.WHATSAPP_FLOWS_IMAGE_ORIGINS;
      else process.env.WHATSAPP_FLOWS_IMAGE_ORIGINS = original;
    }
  });
  it('rejects expired tokens', async () => {
    session.expiresAt = new Date(0);
    await expect(exchange(service, 'SEARCH')).rejects.toThrow('FLOW_EXPIRED');
  });
  it('uses backend category membership and records only offered products', async () => {
    expect(
      (await exchange(service, 'SEARCH', { category: 'Other' })).screen,
    ).toBe('SEARCH');
    const results = await exchange(service, 'SEARCH', {
      category: 'Dairy',
      query: 'milk',
    });
    expect(results.data.products[0]).toMatchObject({
      id: 'p1',
      description: 'USD 2.00 · In stock',
    });
    expect(
      (
        await exchange(service, 'RESULTS', {
          product: 'another-business-product',
        })
      ).screen,
    ).toBe('RESULTS');
    expect(db.product.findFirst).not.toHaveBeenCalled();
    expect((await exchange(service, 'RESULTS', { product: 'p1' })).screen).toBe(
      'PRODUCT',
    );
    expect(db.product.findFirst.mock.calls[0][0].where).toMatchObject({
      businessId: 'b1',
      status: 'ACTIVE',
    });
  });
  it('adds using backend prices and does not repeat additions on retries', async () => {
    await exchange(service, 'SEARCH', { category: 'all' });
    await exchange(service, 'RESULTS', { product: 'p1' });
    expect(
      (await exchange(service, 'PRODUCT', { quantity: '-1' })).screen,
    ).toBe('PRODUCT');
    const first = await exchange(service, 'PRODUCT', {
      quantity: '2',
      price: 0.01,
    });
    expect(first.screen).toBe('DONE');
    expect(db.cartItem.create.mock.calls[0][0].data).toMatchObject({
      unitPrice: 2,
      quantity: 2,
      lineTotal: 4,
    });
    expect(await exchange(service, 'PRODUCT', { quantity: '2' })).toEqual(
      first,
    );
    expect(db.cartItem.create).toHaveBeenCalledTimes(1);
  });
  it('rechecks stock and currency before modifying the basket', async () => {
    session.selectionJson = JSON.stringify({ selected: 'p1', productData: {} });
    expect((await exchange(service, 'PRODUCT', { quantity: '6' })).screen).toBe(
      'PRODUCT',
    );
    db.cart.findFirst.mockResolvedValue({
      id: 'cart',
      currency: 'ZAR',
      items: [{ quantity: 1 }],
    });
    expect((await exchange(service, 'PRODUCT', { quantity: '1' })).screen).toBe(
      'PRODUCT',
    );
    expect(db.cartItem.create).not.toHaveBeenCalled();
  });
  it('does not fetch unapproved image origins', async () => {
    expect(await (service as any).image('http://127.0.0.1/private')).toMatch(
      /^iVBOR/,
    );
  });
  it('offers hosted card checkout only for enabled live providers and an owned pending order', async () => {
    db.payment.findFirst.mockResolvedValue({
      gateway: 'pesepay',
      paymentLink: 'https://payments.example/session',
    });
    expect(await service.cardCheckout('b1', session.phone, 'order')).toBe(
      'https://payments.example/session',
    );
    expect(db.payment.findFirst.mock.calls[0][0].where).toMatchObject({
      businessId: 'b1',
      orderId: 'order',
      order: { customerPhone: session.phone, paymentStatus: 'UNPAID' },
    });
    db.payment.findFirst.mockResolvedValue({
      gateway: 'pesepay',
      paymentLink: 'http://payments.example/session',
    });
    expect(await service.cardCheckout('b1', session.phone, 'order')).toBeNull();
  });
});
