import http from 'http';
import { createMockShopifySessionToken } from '../src/lib/auth/sessionToken';

const BASE_URL = 'http://localhost:3000';
const mockSessionToken = createMockShopifySessionToken('quickstart-1a79b82e.myshopify.com', {
  secret: process.env.SHOPIFY_API_SECRET || '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',
  apiKey: process.env.SHOPIFY_API_KEY || 'fcf3c95da56ecc483ade6dabbdb49e92',
  expiresInSeconds: 3600,
});

let passed = 0;
let failed = 0;

function logTest(success: boolean, name: string, details?: string) {
  if (success) {
    console.log(`  ✓ [PASS] ${name}${details ? ` -> ${details}` : ''}`);
    passed++;
  } else {
    console.error(`  ✕ [FAIL] ${name}${details ? ` -> ${details}` : ''}`);
    failed++;
  }
}

async function request(urlPath: string, method = 'GET', body?: unknown, headers: Record<string, string> = {}): Promise<{ status: number; text: string; json?: any; headers: any }> {
  const url = new URL(urlPath, BASE_URL);
  const options: RequestInit = {
    method,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${mockSessionToken}`,
      ...headers,
    },
    body: body ? JSON.stringify(body) : undefined,
  };

  const res = await fetch(url.toString(), options);
  const text = await res.text();
  let json;
  try {
    json = JSON.parse(text);
  } catch {}

  return { status: res.status, text, json, headers: Object.fromEntries(res.headers.entries()) };
}

async function runE2EVerification() {
  console.log('\n======================================================');
  console.log('🚀 LIVE END-TO-END VERIFICATION: META SHOPIFY CONNECTOR');
  console.log(`📡 Testing against live server: ${BASE_URL}`);
  console.log('======================================================\n');

  // 1. FRONTEND PAGES
  console.log('🖥️ 1. Verifying Merchant UI Dashboard Pages (App Router):');
  const pages = [
    { path: '/', name: 'Overview Dashboard' },
    { path: '/onboarding', name: '8-Step Onboarding Wizard' },
    { path: '/catalog', name: 'Catalog & Feed Manager' },
    { path: '/pixel', name: 'Pixel & CAPI Center' },
    { path: '/events', name: 'Live Event Stream' },
    { path: '/pricing', name: 'Pricing & Plans Dashboard' },
    { path: '/diagnostics', name: 'Diagnostics & Audit Trail' },
    { path: '/settings', name: 'Settings & Credentials' },
  ];

  for (const p of pages) {
    try {
      const res = await request(p.path);
      const isOk = res.status === 200 && res.text.includes('<!DOCTYPE html>');
      logTest(isOk, `${p.name} (${p.path})`, `HTTP ${res.status}`);
    } catch (err: any) {
      logTest(false, `${p.name} (${p.path})`, err.message);
    }
  }

  // 2. LIVE SHOPIFY STORE API
  console.log('\n🏬 2. Verifying Live Store API:');
  try {
    const res = await request('/api/shops');
    const isOk = res.status === 200 && res.json?.success === true && res.json?.totalStores >= 1;
    logTest(isOk, 'GET /api/shops', `Found ${res.json?.totalStores} live store: ${res.json?.shops[0]?.domain}`);
  } catch (err: any) {
    logTest(false, 'GET /api/shops', err.message);
  }

  // 3. CATALOG FEEDS (XML & CSV)
  console.log('\n📦 3. Verifying Meta Commerce Catalog Feeds:');
  try {
    const resXml = await request('/api/catalog/feed/meta.xml?shop=quickstart-1a79b82e.myshopify.com');
    const isXmlOk = resXml.status === 200 && resXml.text.includes('<rss xmlns:g="http://base.google.com/ns/1.0"');
    logTest(isXmlOk, 'GET /api/catalog/feed/meta.xml', `Content-Type: ${resXml.headers['content-type']}`);

    const resCsv = await request('/api/catalog/feed/meta.csv?shop=quickstart-1a79b82e.myshopify.com');
    const isCsvOk = resCsv.status === 200 && resCsv.text.includes('id,item_group_id,title');
    logTest(isCsvOk, 'GET /api/catalog/feed/meta.csv', `CSV feed generated with headers`);
  } catch (err: any) {
    logTest(false, 'Catalog Feeds', err.message);
  }

  // 4. CONVERSIONS API (CAPI) & DEDUPLICATION
  console.log('\n📡 4. Verifying Conversions API (CAPI) Event Ingestion:');
  try {
    const capiPayload = {
      shopDomain: 'quickstart-1a79b82e.myshopify.com',
      eventName: 'AddToCart',
      eventId: `e2e_cart_${Date.now()}`,
      eventSourceUrl: 'https://quickstart-1a79b82e.myshopify.com/products/sample-item',
      userData: {
        email: 'merchant.owner@digi-horizon.com',
        phone: '+1 555-019-2834',
        clientIp: '198.51.100.25',
      },
      customData: {
        currency: 'USD',
        value: 49.00,
        content_ids: ['shopify_US_live_1'],
      },
      testEventCode: 'TEST_DIGI_HORIZON',
    };

    const resCapi = await request('/api/capi/events', 'POST', capiPayload);
    const isCapiOk = resCapi.status === 200 && resCapi.json?.success === true;
    logTest(isCapiOk, 'POST /api/capi/events (AddToCart)', `Event ID: ${resCapi.json?.eventId}, Deduplication Ready`);

    const resTest = await request('/api/capi/test', 'POST', {
      shopDomain: 'quickstart-1a79b82e.myshopify.com',
      eventName: 'Purchase',
      value: 99.00,
      testEventCode: 'TEST_DIGI_HORIZON',
    });
    const isTestOk = resTest.status === 200 && resTest.json?.success === true;
    logTest(isTestOk, 'POST /api/capi/test (Live Purchase)', `Meta Test Event Delivered`);
  } catch (err: any) {
    logTest(false, 'CAPI Ingestion', err.message);
  }

  // 5. CATALOG SYNC & ASYNC QUEUE
  console.log('\n⚙️ 5. Verifying Async Job Queue & Catalog Syncer:');
  try {
    const resSync = await request('/api/catalog/sync', 'POST', {
      shopDomain: 'quickstart-1a79b82e.myshopify.com',
      forceFull: true,
    });
    const syncId = resSync.json?.jobId || resSync.json?.syncId;
    const isSyncOk = resSync.status === 200 && resSync.json?.success === true && !!syncId;
    logTest(isSyncOk, 'POST /api/catalog/sync', `Sync ID: ${syncId}, Status: ${resSync.json?.status}`);
  } catch (err: any) {
    logTest(false, 'Catalog Sync Queue', err.message);
  }

  // 6. DIAGNOSTICS & AUDIT LOGS
  console.log('\n🩺 6. Verifying Health Diagnostics & PII-Masked Logs:');
  try {
    const resDiag = await request('/api/diagnostics');
    const isDiagOk = resDiag.status === 200 && resDiag.json?.success === true;
    logTest(isDiagOk, 'GET /api/diagnostics', `CAPI Health: ${resDiag.json?.health?.capiStatus}`);
  } catch (err: any) {
    logTest(false, 'Diagnostics API', err.message);
  }

  // 7. PRICING & ADMIN PLANS API
  console.log('\n💳 7. Verifying Pricing Plans & Admin Customizer APIs:');
  try {
    // GET /api/plans
    const resPlans = await request('/api/plans?shop=quickstart-1a79b82e.myshopify.com');
    const isPlansOk = resPlans.status === 200 && resPlans.json?.success === true && resPlans.json?.plans?.length >= 3;
    logTest(isPlansOk, 'GET /api/plans', `Returned ${resPlans.json?.plans?.length} plans, Active plan: ${resPlans.json?.usage?.planName}`);

    // POST /api/plans/select (Switch to Accelerate)
    const resSelect = await request('/api/plans/select', 'POST', {
      shop_domain: 'quickstart-1a79b82e.myshopify.com',
      plan_id: 'accelerate',
    });
    const isSelectOk = resSelect.status === 200 && resSelect.json?.success === true && resSelect.json?.plan === 'accelerate';
    logTest(isSelectOk, 'POST /api/plans/select (Accelerate)', `Status: ${resSelect.json?.status}`);

    // PUT /api/plans/admin (Admin customize plan price & features)
    const resAdmin = await request('/api/plans/admin', 'PUT', {
      plan_id: 'growth',
      updates: {
        price: 13,
        sku_limit: 10000,
        support: 'Chat/Email Support',
      },
    });
    const isAdminOk = resAdmin.status === 200 && resAdmin.json?.success === true && resAdmin.json?.plan?.price === 13;
    logTest(isAdminOk, 'PUT /api/plans/admin (Customize Plan)', `Updated plan: ${resAdmin.json?.plan?.name}`);
  } catch (err: any) {
    logTest(false, 'Pricing API Tests', err.message);
  }

  // 8. SAAS ADMIN DASHBOARD & STORE MANAGEMENT API
  console.log('\n📊 8. Verifying SaaS Admin Dashboard & Multi-Store Management:');
  try {
    // 8a. SaaS Admin Page Route
    const resSaasPage = await request('/saas-admin');
    const isSaasPageOk = resSaasPage.status === 200 && resSaasPage.text.includes('<!DOCTYPE html>');
    logTest(isSaasPageOk, 'GET /saas-admin (SaaS Dashboard UI)', `HTTP ${resSaasPage.status}`);

    // 8b. Admin Login API
    const resLogin = await request('/api/saas-admin/auth/login', 'POST', {
      email: 'admin@meta-connector.app',
      password: 'admin1234',
    });
    const isLoginOk = resLogin.status === 200 && resLogin.json?.success === true && !!resLogin.json?.token;
    const adminToken = resLogin.json?.token || '';
    logTest(isLoginOk, 'POST /api/saas-admin/auth/login', `Authenticated as ${resLogin.json?.admin?.name} (${resLogin.json?.admin?.role})`);

    // 8c. Overview Metrics & Charts
    const resOverview = await request('/api/saas-admin/overview?mode=all', 'GET', undefined, {
      'Authorization': `Bearer ${adminToken}`,
    });
    const isOverviewOk =
      resOverview.status === 200 &&
      resOverview.json?.success === true &&
      resOverview.json?.summary?.totalStores > 0 &&
      resOverview.json?.charts?.installationsTrend?.length === 12;
    logTest(
      isOverviewOk,
      'GET /api/saas-admin/overview',
      `Stores: ${resOverview.json?.summary?.totalStores}, MRR: $${resOverview.json?.summary?.monthlyRecurringRevenue}, 4 Charts populated`
    );

    // 8d. All Stores Paginated Query
    const resStores = await request('/api/saas-admin/stores?page=1&pageSize=10&mode=all', 'GET', undefined, {
      'Authorization': `Bearer ${adminToken}`,
    });
    const isStoresOk =
      resStores.status === 200 &&
      resStores.json?.success === true &&
      resStores.json?.stores?.length > 0;
    logTest(
      isStoresOk,
      'GET /api/saas-admin/stores',
      `Returned ${resStores.json?.stores?.length} stores (Total: ${resStores.json?.pagination?.total})`
    );

    // 8e. Store Details Deep View
    const targetStoreId = resStores.json?.stores?.[0]?.id || 'shop_aurora_apparel';
    const resStoreDetails = await request(`/api/saas-admin/stores/${encodeURIComponent(targetStoreId)}`, 'GET', undefined, {
      'Authorization': `Bearer ${adminToken}`,
    });
    const isDetailsOk =
      resStoreDetails.status === 200 &&
      resStoreDetails.json?.success === true &&
      !!resStoreDetails.json?.store?.shopify_domain;
    logTest(
      isDetailsOk,
      `GET /api/saas-admin/stores/[id] (${targetStoreId})`,
      `Store: ${resStoreDetails.json?.store?.shop_name}, Domain: ${resStoreDetails.json?.store?.shopify_domain}`
    );

    // 8f. Subscriptions & Verified Billing
    const resSubs = await request('/api/saas-admin/subscriptions?mode=all', 'GET', undefined, {
      'Authorization': `Bearer ${adminToken}`,
    });
    const isSubsOk =
      resSubs.status === 200 &&
      resSubs.json?.success === true &&
      resSubs.json?.metrics?.totalMRR > 0;
    logTest(
      isSubsOk,
      'GET /api/saas-admin/subscriptions',
      `Active Paid: ${resSubs.json?.metrics?.activePaidSubscriptions}, Verified MRR: $${resSubs.json?.metrics?.totalMRR}`
    );

    // 8g. Activity Logs
    const resLogs = await request('/api/saas-admin/activity-logs?limit=10', 'GET', undefined, {
      'Authorization': `Bearer ${adminToken}`,
    });
    const isLogsOk = resLogs.status === 200 && resLogs.json?.success === true && resLogs.json?.logs?.length > 0;
    logTest(isLogsOk, 'GET /api/saas-admin/activity-logs', `Loaded ${resLogs.json?.logs?.length} recent activity events`);

    // 8h. Notifications Alerts
    const resNotifs = await request('/api/saas-admin/notifications', 'GET', undefined, {
      'Authorization': `Bearer ${adminToken}`,
    });
    const isNotifsOk = resNotifs.status === 200 && resNotifs.json?.success === true;
    logTest(isNotifsOk, 'GET /api/saas-admin/notifications', `Loaded notifications alerts`);
  } catch (err: any) {
    logTest(false, 'SaaS Admin E2E Tests', err.message);
  }

  console.log('\n======================================================');
  console.log(`📊 LIVE E2E RESULTS: ${passed} PASSED, ${failed} FAILED`);
  console.log('======================================================\n');

  if (failed > 0) {
    process.exit(1);
  } else {
    process.exit(0);
  }
}

runE2EVerification().catch((err) => {
  console.error('Fatal E2E error:', err);
  process.exit(1);
});
