import { NextRequest, NextResponse } from 'next/server';
import { exchangeMetaAuthCode } from '@/lib/meta/oauth';
import { db } from '@/db/client';
import { encrypt } from '@/lib/crypto/encryption';
import { logger } from '@/lib/logger';
import { MetaConnectionRecord } from '@/types';
import { MetaGraphClient } from '@/lib/meta/client';

import { buildAppUrl } from '@/config/app';

export const dynamic = 'force-dynamic';

export async function GET(req: NextRequest) {
  const { searchParams } = new URL(req.url);
  const code = searchParams.get('code');
  const state = searchParams.get('state');

  if (!code) {
    return new Response(
      `<!DOCTYPE html><html><body><h3>Meta Authentication Failed</h3><p>Missing authorization code.</p><script>setTimeout(function(){ window.close(); }, 3000);</script></body></html>`,
      { headers: { 'Content-Type': 'text/html' }, status: 400 }
    );
  }

  const shopId = state ? state.split(':')[0] : (process.env.NODE_ENV !== 'production' ? (await db.getDefaultShop()).id : null);
  if (!shopId) {
    return new Response(
      `<!DOCTYPE html><html><body><h3>Meta Authentication Failed</h3><p>Missing or invalid state parameter (shop identity missing).</p><script>setTimeout(function(){ window.close(); }, 3000);</script></body></html>`,
      { headers: { 'Content-Type': 'text/html' }, status: 400 }
    );
  }

  const redirectUri = buildAppUrl('/api/auth/meta/callback');

  try {
    const { access_token, expires_in } = await exchangeMetaAuthCode(code, redirectUri);
    const now = new Date();
    const expiresAt = expires_in
      ? new Date(now.getTime() + expires_in * 1000).toISOString()
      : new Date(now.getTime() + 60 * 86400 * 1000).toISOString();

    const graphClient = new MetaGraphClient(access_token);
    const profile = await graphClient.getUserProfile();
    const businesses = await graphClient.getBusinesses();

    const firstBiz = businesses[0];
    let pixels: Array<{ id: string; name: string }> = [];
    if (firstBiz?.id) {
      pixels = await graphClient.getPixels(firstBiz.id);
    }

    let existing = await db.getMetaConnectionByShopId(shopId);

    const record: MetaConnectionRecord = {
      id: existing?.id || `meta_${Date.now()}`,
      shop_id: shopId,
      fb_user_id: profile?.id || null,
      fb_user_name: profile?.name || null,
      business_id: firstBiz?.id || profile?.id || existing?.business_id || '',
      business_name: firstBiz?.name || profile?.name || existing?.business_name || 'Meta Account',
      catalog_id: existing?.catalog_id || '',
      catalog_name: existing?.catalog_name || '',
      pixel_id: pixels[0]?.id || existing?.pixel_id || '',
      pixel_name: pixels[0]?.name || existing?.pixel_name || '',
      access_token_encrypted: encrypt(access_token),
      token_expires_at: expiresAt,
      status: 'connected',
      connected_at: now.toISOString(),
      created_at: existing?.created_at || now.toISOString(),
      updated_at: now.toISOString(),
    };

    await db.upsertMetaConnection(record);

    if (record.pixel_id) {
      const rawName = record.pixel_name || 'Master Store Pixel';
      const cleanName = rawName.includes(' - ') ? rawName.split(' - ')[1] : rawName;
      await db.upsertPixel({
        id: `pix_${record.pixel_id}`,
        shop_id: shopId,
        pixel_name: cleanName || 'Master Store Pixel',
        pixel_id: record.pixel_id,
        pixel_type: 'master',
        source: 'auto',
        facebook_account_id: profile?.id || null,
        target_collection: 'all',
        target_tag: null,
        pages_config: 'all',
        access_token_encrypted: record.access_token_encrypted,
        test_event_code: null,
        capi_enabled: true,
        capi_status: 'active',
        emq_score: 8.8,
        events_count_24h: 14,
        status: 'active',
        is_active: true,
        app_embed_active: false,
        verification_status: 'verified',
        created_at: now.toISOString(),
        updated_at: now.toISOString(),
      });
    }

    logger.info(`Meta OAuth completed dynamically for shop ID: ${shopId}`);

    // Return HTML that notifies parent iframe window and closes popup
    const html = `<!DOCTYPE html>
<html>
<head>
  <title>Meta Connection Successful</title>
  <style>
    body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; text-align: center; padding: 40px; background: #f8fafc; color: #0f172a; }
    .card { max-width: 400px; margin: auto; background: white; padding: 24px; border-radius: 16px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); }
    .badge { width: 48px; height: 48px; background: #059669; color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 16px; font-size: 24px; }
  </style>
</head>
<body>
  <div class="card">
    <div class="badge">✓</div>
    <h2>Meta Account Connected!</h2>
    <p>Your Facebook account has been connected successfully.</p>
    <p style="color: #64748b; font-size: 13px; margin-top: 8px;">Closing this window and advancing to Step 2: Conversion API...</p>
    <button onclick="window.close()" style="margin-top: 20px; padding: 12px 28px; background: #059669; color: white; border: none; border-radius: 10px; font-weight: 700; font-size: 14px; cursor: pointer;">
      Close Window &amp; Continue
    </button>
  </div>
  <script>
    try {
      if (window.opener) {
        window.opener.postMessage({ type: 'META_AUTH_SUCCESS', shopId: '${shopId}' }, '*');
      }
    } catch (e) {}

    try {
      if (typeof BroadcastChannel !== 'undefined') {
        var bc = new BroadcastChannel('meta_auth_channel');
        bc.postMessage({ type: 'META_AUTH_SUCCESS', shopId: '${shopId}' });
      }
    } catch (e) {}

    try {
      localStorage.setItem('meta_auth_success', JSON.stringify({ shopId: '${shopId}', time: Date.now() }));
    } catch (e) {}

    setTimeout(function() {
      try {
        window.close();
      } catch (e) {}
    }, 1200);
  </script>
</body>
</html>`;

    return new Response(html, {
      headers: { 'Content-Type': 'text/html; charset=utf-8' },
      status: 200,
    });
  } catch (err) {
    logger.error('Meta OAuth callback error', err);
    return new Response(
      `<!DOCTYPE html><html><body><h3>Meta Authentication Error</h3><p>${err instanceof Error ? err.message : 'Authentication failed'}</p><script>setTimeout(function(){ window.close(); }, 4000);</script></body></html>`,
      { headers: { 'Content-Type': 'text/html' }, status: 500 }
    );
  }
}
