import { NextRequest, NextResponse } from 'next/server';
import { getAuthenticatedStore } from '@/lib/auth/storeContext';
import { getShopifyAccessToken } from '@/lib/shopify/token-manager';
import { logger } from '@/lib/logger';
import { db } from '@/db/client';

export const dynamic = 'force-dynamic';

async function probeStorefront(domain: string): Promise<boolean> {
  try {
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), 6000);
    const res = await fetch(`https://${domain}/`, {
      signal: controller.signal,
      headers: {
        'User-Agent':
          'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
      },
      redirect: 'follow',
      cache: 'no-store',
    });
    clearTimeout(timeout);

    if (res.ok) {
      const html = await res.text();
      if (
        html.includes('meta-commerce-pixel-embed') ||
        html.includes('meta-pixel.js') ||
        html.includes('Meta Pixel & CAPI Tracker') ||
        html.includes('meta-commerce-pixel-con')
      ) {
        return true;
      }
    }
  } catch (err) {
    logger.warn(`[VerifyAppEmbed] Storefront probe failed for ${domain}: ${err instanceof Error ? err.message : String(err)}`);
  }
  return false;
}

async function checkThemeSettings(domain: string): Promise<{ checked: boolean; found: boolean; active: boolean }> {
  try {
    const token = await getShopifyAccessToken(domain).catch(() => null);
    if (!token) return { checked: false, found: false, active: false };

    // Query active theme via REST
    const themesRes = await fetch(`https://${domain}/admin/api/2024-07/themes.json`, {
      headers: {
        'X-Shopify-Access-Token': token,
        'Content-Type': 'application/json',
      },
      cache: 'no-store',
    });

    if (!themesRes.ok) return { checked: false, found: false, active: false };
    const themesData = await themesRes.json();
    const mainTheme = themesData.themes?.find((t: { role?: string }) => t.role === 'main');
    if (!mainTheme?.id) return { checked: false, found: false, active: false };

    // Fetch config/settings_data.json
    const assetRes = await fetch(
      `https://${domain}/admin/api/2024-07/themes/${mainTheme.id}/assets.json?asset[key]=config/settings_data.json`,
      {
        headers: {
          'X-Shopify-Access-Token': token,
          'Content-Type': 'application/json',
        },
        cache: 'no-store',
      }
    );

    if (!assetRes.ok) return { checked: false, found: false, active: false };
    const assetData = await assetRes.json();
    const settings = JSON.parse(assetData.asset?.value || '{}');

    const current = settings.current || settings;
    const blocks = current.blocks || {};

    for (const key of Object.keys(blocks)) {
      const block = blocks[key];
      if (!block || typeof block !== 'object') continue;
      const type = String(block.type || '').toLowerCase();
      const isEmbed =
        type.includes('pixel_embed') ||
        type.includes('meta-commerce-pixel') ||
        type.includes('meta-sync-pixel') ||
        type.includes('35913d5a-5d1f-1f3f-513a-29faaf412c6711065daf') ||
        type.includes('d6d73fa2d424638f91826f822d89c51f');

      if (isEmbed) {
        const isActive = block.disabled !== true;
        return { checked: true, found: true, active: isActive };
      }
    }

    return { checked: true, found: false, active: false };
  } catch (err) {
    logger.warn(`[VerifyAppEmbed] Theme settings check failed for ${domain}: ${err instanceof Error ? err.message : String(err)}`);
    return { checked: false, found: false, active: false };
  }
}

async function handleVerification(req: NextRequest) {
  try {
    let targetShop = '';

    if (req.method === 'POST') {
      try {
        const body = await req.json();
        if (body?.shop) targetShop = String(body.shop).trim();
      } catch {}
    }

    if (!targetShop) {
      targetShop =
        req.nextUrl.searchParams.get('shop') ||
        req.nextUrl.searchParams.get('shopify_domain') ||
        '';
    }

    if (!targetShop) {
      const authStore = await getAuthenticatedStore(req);
      if (authStore?.shopify_domain) {
        targetShop = authStore.shopify_domain;
      }
    }

    if (!targetShop) {
      return NextResponse.json(
        { success: false, verified: false, message: 'Shop domain is required for embed verification' },
        { status: 400 }
      );
    }

    const cleanShop = targetShop
      .replace(/^https?:\/\//, '')
      .replace(/\/.*$/, '')
      .trim()
      .toLowerCase();
    const fullDomain = cleanShop.includes('.') ? cleanShop : `${cleanShop}.myshopify.com`;

    // 1. Layer 1: Probing storefront HTML
    const isStorefrontActive = await probeStorefront(fullDomain);
    if (isStorefrontActive) {
      const store = await db.getShopByDomain(fullDomain);
      if (store) {
        await db.setAppEmbedActiveForShop(store.id, true);
      }
      return NextResponse.json({
        success: true,
        verified: true,
        method: 'storefront',
        message: 'Theme App Embed is verified active on storefront.',
      });
    }

    // 2. Layer 2: Check Theme settings_data.json via Admin API
    const themeCheck = await checkThemeSettings(fullDomain);
    if (themeCheck.checked) {
      if (themeCheck.found && themeCheck.active) {
        const store = await db.getShopByDomain(fullDomain);
        if (store) {
          await db.setAppEmbedActiveForShop(store.id, true);
        }
        return NextResponse.json({
          success: true,
          verified: true,
          method: 'theme_settings',
          message: 'Theme App Embed is active and enabled in your live theme.',
        });
      }

      if (themeCheck.found && !themeCheck.active) {
        return NextResponse.json({
          success: true,
          verified: false,
          method: 'theme_settings',
          message:
            "Meta Pixel app embed was found in your theme settings, but is currently turned OFF. In Theme Editor, expand App Embeds in the left sidebar, toggle ON 'Meta Pixel & CAPI Tracker', and click Save.",
        });
      }

      return NextResponse.json({
        success: true,
        verified: false,
        method: 'theme_settings',
        message:
          "Theme App Embed has not been enabled in your active theme yet. Please click 'Open Theme Editor', toggle ON 'Meta Pixel & CAPI Tracker', and click Save.",
      });
    }

    // 3. Fallback when neither probe detected it
    return NextResponse.json({
      success: true,
      verified: false,
      method: 'not_detected',
      message:
        "Theme App Embed was not detected on your live theme. Please open Theme Editor, turn ON 'Meta Pixel & CAPI Tracker' in App Embeds, click Save, and verify again.",
    });
  } catch (err) {
    logger.error(`[VerifyAppEmbed] Unexpected error: ${err instanceof Error ? err.message : String(err)}`);
    return NextResponse.json(
      {
        success: false,
        verified: false,
        error: err instanceof Error ? err.message : 'Internal verification error',
        message: 'Failed to verify App Embed status due to server error.',
      },
      { status: 500 }
    );
  }
}

export async function GET(req: NextRequest) {
  return handleVerification(req);
}

export async function POST(req: NextRequest) {
  return handleVerification(req);
}
