import { beforeEach, describe, expect, it, vi } from 'vitest';

import { fetchMerchantContacts } from '@/services/merchantService';
import { getSupabaseClient } from '@/lib/supabase';

vi.mock('@/lib/supabase', () => ({
  getSupabaseClient: vi.fn(),
}));

type QueryResponse = {
  data: unknown[] | null;
  error: { code?: string; message: string } | null;
};

function createQuery(response: QueryResponse) {
  const query = {
    order: vi.fn(() => query),
    in: vi.fn(() => query),
    then: (onFulfilled: (value: QueryResponse) => unknown, onRejected?: (reason: unknown) => unknown) =>
      Promise.resolve(response).then(onFulfilled, onRejected),
    catch: (onRejected: (reason: unknown) => unknown) => Promise.resolve(response).catch(onRejected),
  };

  return query;
}

function createSupabaseMock(responses: Record<string, QueryResponse>) {
  return {
    from: vi.fn((table: string) => ({
      select: vi.fn(() => createQuery(responses[table] ?? { data: [], error: null })),
    })),
  };
}

describe('fetchMerchantContacts', () => {
  beforeEach(() => {
    vi.resetAllMocks();
  });

  it('falls back to final_result_products when merchant_contacts is empty', async () => {
    vi.mocked(getSupabaseClient).mockReturnValue(createSupabaseMock({
      merchant_contacts: { data: [], error: null },
      final_result_products: {
        data: [{
          id: 'fr-001',
          batch_id: 'BATCH-001',
          material_id: 'mat-001',
          offer_url: 'https://detail.1688.com/offer/1.html',
          merchant_name: '杭州测试供应商',
          merchant_url: 'https://shop.1688.com/a',
          contact_page_url: 'https://shop.1688.com/a/contact',
          detected_contacts: [{ type: 'phone', value: '13800138000' }],
          created_at: '2026-04-09T10:00:00.000Z',
        }],
        error: null,
      },
      standardized_results: {
        data: [{ material_id: 'mat-001', standardized_name: 'PVC-U给水管 DN100' }],
        error: null,
      },
    }) as unknown as ReturnType<typeof getSupabaseClient>);

    await expect(fetchMerchantContacts()).resolves.toEqual([
      expect.objectContaining({
        id: 'fr-001',
        merchant_name: '杭州测试供应商',
        standardized_name: 'PVC-U给水管 DN100',
        phone: '13800138000',
        mobile: '13800138000',
      }),
    ]);
  });

  it('lets curated merchant_contacts override fallback values while preserving phone fallback', async () => {
    vi.mocked(getSupabaseClient).mockReturnValue(createSupabaseMock({
      merchant_contacts: {
        data: [{
          id: 'mc-001',
          merchant_url: 'https://shop.1688.com/a',
          merchant_name: '人工维护供应商',
          contact_page_url: '',
          standardized_name: '',
          contact_person: '王经理',
          phone: '0571-88886666',
          mobile: '',
          address: '浙江杭州',
          source_batch_id: 'BATCH-MANUAL',
          source_offer_url: '',
          created_at: '2026-04-08T08:00:00.000Z',
          updated_at: '2026-04-10T08:00:00.000Z',
          updated_by: 'alice',
        }],
        error: null,
      },
      final_result_products: {
        data: [{
          id: 'fr-001',
          batch_id: 'BATCH-001',
          material_id: 'mat-001',
          offer_url: 'https://detail.1688.com/offer/1.html',
          merchant_name: '流程产出供应商',
          merchant_url: 'https://shop.1688.com/a',
          contact_page_url: 'https://shop.1688.com/a/contact',
          detected_contacts: [{ type: 'mobile', value: '13800138000' }],
          created_at: '2026-04-09T10:00:00.000Z',
        }],
        error: null,
      },
      standardized_results: {
        data: [{ material_id: 'mat-001', standardized_name: 'PPR热水管 S3.2 DN32' }],
        error: null,
      },
    }) as unknown as ReturnType<typeof getSupabaseClient>);

    await expect(fetchMerchantContacts()).resolves.toEqual([
      expect.objectContaining({
        id: 'mc-001',
        merchant_name: '人工维护供应商',
        contact_person: '王经理',
        standardized_name: 'PPR热水管 S3.2 DN32',
        phone: '0571-88886666',
        mobile: '13800138000',
        source_offer_url: 'https://detail.1688.com/offer/1.html',
      }),
    ]);
  });
});
