import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/db/client';
import { env } from '@/lib/config/env';
import { getAuthenticatedStore } from '@/lib/auth/storeContext';
import { decrypt } from '@/lib/crypto/encryption';

export const dynamic = 'force-dynamic';

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const pixelId = String(body.pixelId || '').trim();
    const shopDomain = body.shop || body.shopify_domain;
    let accessToken = String(body.accessToken || '').trim();

    if (!pixelId) {
      return NextResponse.json({
        success: false,
        valid: false,
        error: 'Pixel ID is required for verification.',
      }, { status: 400 });
    }

    if (!/^\d{15,16}$/.test(pixelId)) {
      return NextResponse.json({
        success: true,
        valid: false,
        error: `Pixel ID "${pixelId}" must be a 15 or 16 digit number.`,
      });
    }

    // Resolve shop
    let shop = null;
    if (shopDomain) {
      shop = await db.getShopByDomain(shopDomain);
    }
    if (!shop) {
      shop = await getAuthenticatedStore(req);
    }

    // If no accessToken provided in request, check if we have one saved in DB for this pixel or shop
    if (!accessToken && shop) {
      const pixels = await db.getPixelsByShopId(shop.id);
      const matchedPixel = pixels.find((p) => p.pixel_id === pixelId);
      if (matchedPixel?.access_token_encrypted) {
        try {
          accessToken = decrypt(matchedPixel.access_token_encrypted);
        } catch {}
      }

      if (!accessToken) {
        const metaConn = await db.getMetaConnectionByShopId(shop.id);
        if (metaConn?.access_token_encrypted) {
          try {
            accessToken = decrypt(metaConn.access_token_encrypted);
          } catch {}
        }
      }
    }

    const version = env.meta.graphVersion || 'v20.0';
    let verified = false;
    let pixelName = `Pixel ${pixelId}`;
    let verificationMethod = 'meta_graph';
    let verificationError: string | null = null;

    // 1. If we have a Conversions API access token, verify directly with Meta Graph API
    if (accessToken && !accessToken.startsWith('EAGR')) {
      try {
        const pixelUrl = `https://graph.facebook.com/${version}/${encodeURIComponent(pixelId)}?fields=id,name,is_unavailable&access_token=${encodeURIComponent(accessToken)}`;
        const res = await fetch(pixelUrl, { signal: AbortSignal.timeout(7000), cache: 'no-store' });
        const data = await res.json();

        if (res.ok && data.id) {
          verified = true;
          pixelName = data.name || pixelName;
          verificationMethod = 'meta_graph_direct';
        } else if (data.error) {
          verificationError = data.error.message || 'Meta Graph API returned an error';
        }
      } catch (err: any) {
        verificationError = err.message || 'Connection timeout to Meta Graph API';
      }
    }

    // 2. If token verification wasn't used or failed, probe using App Token
    if (!verified && env.meta.appId && env.meta.appSecret) {
      try {
        const appToken = `${env.meta.appId}|${env.meta.appSecret}`;
        const pixelUrl = `https://graph.facebook.com/${version}/${encodeURIComponent(pixelId)}?fields=id,name&access_token=${encodeURIComponent(appToken)}`;
        const res = await fetch(pixelUrl, { signal: AbortSignal.timeout(6000), cache: 'no-store' });
        const data = await res.json();

        if (res.ok && data.id) {
          verified = true;
          pixelName = data.name || pixelName;
          verificationMethod = 'meta_app_token';
          verificationError = null;
        } else if (data.error && data.error.code === 100 && data.error.message?.includes('Missing Permission')) {
          // (#100) Missing Permission means the Pixel exists on Meta, but requires dataset permissions
          verified = true;
          verificationMethod = 'meta_pixel_exists';
          verificationError = null;
        }
      } catch {}
    }

    // Update pixel status in DB according to real verification result
    if (shop) {
      try {
        const pixels = await db.getPixelsByShopId(shop.id);
        const target = pixels.find((p) => p.pixel_id === pixelId);
        if (target) {
          if (verified) {
            target.verification_status = 'verified';
            target.status = 'active';
            target.is_active = true;
          } else {
            target.verification_status = 'failed';
          }
          await db.upsertPixel(target);
        }
      } catch (err) {
        console.error('Failed to update pixel verification status:', err);
      }
    }

    if (verified) {
      return NextResponse.json({
        success: true,
        valid: true,
        pixelId,
        pixelName,
        verificationMethod,
        message: `Pixel ${pixelId} successfully verified with Meta.`,
      });
    }

    return NextResponse.json({
      success: true,
      valid: false,
      pixelId,
      error: verificationError || `Could not verify Pixel ID ${pixelId} with Meta. Please verify that this ID is correct in Meta Events Manager.`,
    });
  } catch (err: any) {
    return NextResponse.json({
      success: false,
      valid: false,
      error: err.message || 'Server error during Meta pixel verification.',
    }, { status: 500 });
  }
}
