import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/db/client';
import { encrypt } from '@/lib/crypto/encryption';
import { logger } from '@/lib/logger';
import { ShopifyClient } from '@/lib/shopify/client';
import { APP_CONFIG, APP_PATHS, APP_URLS, buildAppUrl } from '@/config/app';
import { SHOPIFY_CONFIG, getShopifySecret } from '@/config/shopify';

import { extractShopDomainFromRequest } from '@/lib/auth/storeContext';

export const dynamic = 'force-dynamic';

export async function GET(req: NextRequest) {
  const url = new URL(req.url);
  let rawShop = url.searchParams.get('shop');
  if (!rawShop) {
    const extracted = extractShopDomainFromRequest(req);
    if (extracted) {
      rawShop = extracted;
    } else if (process.env.NODE_ENV !== 'production') {
      rawShop = SHOPIFY_CONFIG.defaultShopDomain;
    }
  }

  // If no store can be determined, redirect to the branded installation portal
  if (!rawShop) {
    return NextResponse.redirect(buildAppUrl('/api/auth/shopify'));
  }

  const cleanShop = (rawShop || '').includes('.') ? rawShop : `${rawShop}.myshopify.com`;
  const code = url.searchParams.get('code');
  const returnTo = url.searchParams.get('returnTo') || APP_PATHS.pixel;

  const redirectUri = APP_URLS.authCallback();
  const apiKey = SHOPIFY_CONFIG.apiKey;
  const apiSecret = getShopifySecret();
  const scopes = SHOPIFY_CONFIG.scopes;

  // 1. If no authorization code, initiate Shopify OAuth authorize with iframe breakout
  if (!code) {
    const authorizeUrl = `https://${cleanShop}/admin/oauth/authorize?client_id=${apiKey}&scope=${encodeURIComponent(scopes)}&redirect_uri=${encodeURIComponent(redirectUri)}`;

    return new Response(
      `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Redirecting to Shopify Authorization...</title>
  <script>
    try {
      if (window.top && window.top !== window) {
        window.top.location.href = ${JSON.stringify(authorizeUrl)};
      } else {
        window.location.href = ${JSON.stringify(authorizeUrl)};
      }
    } catch (e) {
      window.location.href = ${JSON.stringify(authorizeUrl)};
    }
  </script>
</head>
<body style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; display: flex; justify-content: center; align-items: center; min-height: 80vh; background: #f8fafc; margin: 0;">
  <div style="text-align: center; max-width: 480px; padding: 32px; background: white; border-radius: 12px; box-shadow: 0 4px 16px rgba(0,0,0,0.08); border: 1px solid #e2e8f0;">
    <div style="font-size: 32px; margin-bottom: 12px;">🔒</div>
    <h2 style="margin: 0 0 10px; color: #1e293b; font-size: 20px;">Connecting to Shopify</h2>
    <p style="color: #64748b; font-size: 14px; margin-bottom: 24px; line-height: 1.5;">
      Redirecting to authorize permissions for <strong>${cleanShop}</strong>. If the page does not open automatically, please click below:
    </p>
    <a href="${authorizeUrl}" target="_top" style="display: inline-block; padding: 12px 24px; background: #2563eb; color: white; border-radius: 8px; text-decoration: none; font-weight: 600; font-size: 14px;">
      Authorize App on Shopify &rarr;
    </a>
  </div>
</body>
</html>`,
      {
        status: 200,
        headers: { 'Content-Type': 'text/html; charset=utf-8' },
      }
    );
  }

  // 2. Exchange authorization code for official access token
  let accessToken = '';
  if (code && cleanShop && apiSecret) {
    try {
      const tokenParams = new URLSearchParams({
        client_id: apiKey,
        client_secret: apiSecret,
        code,
        expiring: '1',
      });

      const tokenRes = await fetch(`https://${cleanShop}/admin/oauth/access_token`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' },
        body: tokenParams.toString(),
      });

      if (tokenRes.ok) {
        const tokenData = await tokenRes.json();
        if (tokenData.access_token) {
          accessToken = tokenData.access_token;
          const now = new Date().toISOString();

          logger.info(`[OAuth exchange SUCCESS]: Generated and stored access token starting with: ${accessToken.slice(0, 8)}... for shop: ${cleanShop}`);

          let existingShop = await db.getShopByDomain(cleanShop);
          const shopRecord = {
            id: existingShop?.id || `shop_${Date.now()}`,
            shopify_domain: cleanShop,
            access_token_encrypted: encrypt(accessToken),
            scopes: tokenData.scope ? tokenData.scope.split(',') : scopes.split(','),
            installed_at: existingShop?.installed_at || now,
            status: 'installed' as const,
            plan: existingShop?.plan || 'growth',
            created_at: existingShop?.created_at || now,
            updated_at: now,
          };
          await db.upsertShop(shopRecord);

          // Update app configuration record
          const existingConfig = await db.getAppConfiguration(shopRecord.id) || await db.getAppConfigurationByDomain(cleanShop);
          await db.upsertAppConfiguration({
            id: existingConfig?.id || `config_${shopRecord.id}`,
            shop_id: shopRecord.id,
            shopify_domain: cleanShop,
            shopify_access_token_encrypted: encrypt(accessToken),
            shopify_api_key: apiKey,
            shopify_api_secret_encrypted: encrypt(apiSecret),
            shopify_api_version: SHOPIFY_CONFIG.apiVersion,
            meta_business_id: existingConfig?.meta_business_id || null,
            meta_business_name: existingConfig?.meta_business_name || null,
            meta_catalog_id: existingConfig?.meta_catalog_id || null,
            meta_catalog_name: existingConfig?.meta_catalog_name || null,
            meta_pixel_id: existingConfig?.meta_pixel_id || null,
            meta_pixel_name: existingConfig?.meta_pixel_name || null,
            meta_access_token_encrypted: existingConfig?.meta_access_token_encrypted || null,
            meta_test_event_code: existingConfig?.meta_test_event_code || null,
            created_at: existingConfig?.created_at || now,
            updated_at: now,
          });

          // Trigger initial live product synchronization
          try {
            const client = new ShopifyClient(cleanShop, accessToken);
            const products = await client.fetchAllProductsForCatalog(shopRecord.id);
            await db.clearProductsByShopId(shopRecord.id);
            for (const prod of products) {
              await db.upsertProduct(prod);
            }
            logger.info(`[OAuth sync]: Synced ${products.length} products on authorization for ${cleanShop}`);
          } catch (syncErr) {
            logger.warn(`[OAuth sync warning]: ${syncErr instanceof Error ? syncErr.message : String(syncErr)}`);
          }
        }
      } else {
        const errorText = await tokenRes.text();
        logger.error(`[OAuth access_token HTTP error]: ${tokenRes.status} ${errorText}`);
      }
    } catch (err: any) {
      logger.error('[OAuth token exchange error]', err);
    }
  }

  // 3. Break back into Shopify Admin embedded frame or dashboard
  const shopSubdomain = cleanShop.replace(/\.myshopify\.com$/i, '');
  const appHandle = process.env.SHOPIFY_APP_HANDLE || process.env.SHOPIFY_API_KEY || 'meta-connector';

  const cleanSubPath = returnTo.replace(/^\/(?:app|meta-connector)\/?/, '').trim();
  const subRoute = cleanSubPath ? (cleanSubPath.startsWith('/') ? cleanSubPath : `/${cleanSubPath}`) : '/pixel';
  const targetAppUrl = `https://admin.shopify.com/store/${shopSubdomain}/apps/${appHandle}/meta-connector${subRoute}`;

  return new Response(
    `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Authorization Completed</title>
  <script>
    try {
      if (window.top && window.top !== window) {
        window.top.location.href = ${JSON.stringify(targetAppUrl)};
      } else {
        window.location.href = ${JSON.stringify(`/meta-connector${subRoute}?shop=${encodeURIComponent(cleanShop)}`)};
      }
    } catch (e) {
      window.location.href = ${JSON.stringify(`/meta-connector${subRoute}?shop=${encodeURIComponent(cleanShop)}`)};
    }
  </script>
</head>
<body style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; display: flex; justify-content: center; align-items: center; min-height: 80vh; margin: 0; background: #f8fafc;">
  <div style="text-align: center; max-width: 420px; padding: 32px; background: white; border-radius: 12px; box-shadow: 0 4px 16px rgba(0,0,0,0.06); border: 1px solid #e2e8f0;">
    <div style="font-size: 32px; margin-bottom: 12px;">✅</div>
    <h3 style="margin: 0 0 8px; color: #1e293b; font-size: 18px;">Authorization Completed</h3>
    <p style="color: #64748b; font-size: 14px; margin-bottom: 20px;">Successfully connected and authorized <strong>${cleanShop}</strong>.</p>
    <a href="${targetAppUrl}" target="_top" style="display: inline-block; padding: 10px 20px; background: #2563eb; color: white; border-radius: 8px; text-decoration: none; font-weight: 600; font-size: 13px;">
      Open App Dashboard &rarr;
    </a>
  </div>
</body>
</html>`,
    {
      status: 200,
      headers: { 'Content-Type': 'text/html; charset=utf-8' },
    }
  );
}
