import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/db/client';
import { decrypt } from '@/lib/crypto/encryption';
import { sendMetaCapiEvents, normalizeUserData, generateEventId } from '@/lib/meta/capi';
import { MetaServerEvent } from '@/types';
import { getAuthenticatedStore, unauthorizedResponse } from '@/lib/auth/storeContext';

export const dynamic = 'force-dynamic';

export async function GET(req: NextRequest) {
  try {
    const shop = await getAuthenticatedStore(req);
    if (!shop) {
      return unauthorizedResponse();
    }

    const { searchParams } = new URL(req.url);
    const limit = parseInt(searchParams.get('limit') || '50', 10);

    // Strictly fetch CAPI events for this store
    const events = await db.getCapiEvents(shop.id, limit);

    return NextResponse.json({
      success: true,
      shopDomain: shop.shopify_domain,
      events,
    });
  } catch (err) {
    return NextResponse.json(
      { success: false, error: err instanceof Error ? err.message : 'Internal Server Error' },
      { status: 500 }
    );
  }
}

export async function POST(req: NextRequest) {
  try {
    const shop = await getAuthenticatedStore(req);
    if (!shop) {
      return unauthorizedResponse();
    }

    const body = await req.json();
    const {
      eventName = 'PageView',
      eventId,
      eventSourceUrl,
      orderId,
      userData = {},
      customData = {},
      testEventCode,
    } = body;

    const metaConn = await db.getMetaConnectionByShopId(shop.id);
    const storePixels = await db.getPixelsByShopId(shop.id);

    // Collect all active CAPI destinations for this store
    interface CapiDestination {
      pixelId: string;
      token: string;
      testCode?: string;
    }
    const destinations: CapiDestination[] = [];
    const seenPixelIds = new Set<string>();

    // 1. Primary Meta connection pixel
    if (metaConn && metaConn.pixel_id && metaConn.access_token_encrypted) {
      try {
        const token = decrypt(metaConn.access_token_encrypted);
        if (token) {
          destinations.push({
            pixelId: metaConn.pixel_id,
            token,
            testCode: metaConn.test_event_code || undefined,
          });
          seenPixelIds.add(metaConn.pixel_id);
        }
      } catch {}
    }

    // 2. Multi-pixels from meta_pixels table
    for (const p of storePixels) {
      if (p.is_active !== false && p.capi_enabled && p.pixel_id && !seenPixelIds.has(p.pixel_id)) {
        let token = '';
        if (p.access_token_encrypted) {
          try { token = decrypt(p.access_token_encrypted); } catch {}
        }
        if (!token && metaConn?.access_token_encrypted) {
          try { token = decrypt(metaConn.access_token_encrypted); } catch {}
        }
        if (token) {
          destinations.push({
            pixelId: p.pixel_id,
            token,
            testCode: p.test_event_code || metaConn?.test_event_code || undefined,
          });
          seenPixelIds.add(p.pixel_id);
        }
      }
    }

    if (destinations.length === 0) {
      return NextResponse.json(
        { success: false, error: 'Meta Pixel with Conversions API is not configured for this shop' },
        { status: 400 }
      );
    }

    // Normalize user data with SHA-256
    const clientIp = req.headers.get('x-forwarded-for')?.split(',')[0] || req.ip || userData.clientIp;
    const userAgent = req.headers.get('user-agent') || userData.userAgent;

    const normalizedUser = normalizeUserData({
      ...userData,
      clientIp,
      userAgent,
    });

    // Deterministic deduplication event_id
    const finalEventId = eventId || generateEventId(eventName.toLowerCase(), orderId);

    const event: MetaServerEvent = {
      event_name: eventName,
      event_time: Math.floor(Date.now() / 1000),
      event_id: finalEventId,
      event_source_url: eventSourceUrl || req.headers.get('referer') || `https://${shop.shopify_domain}`,
      action_source: 'website',
      user_data: normalizedUser,
      custom_data: customData,
    };

    let lastResult: any = null;
    let anySuccess = false;
    for (const dest of destinations) {
      const res = await sendMetaCapiEvents({
        pixelId: dest.pixelId,
        accessToken: dest.token,
        events: [event],
        testEventCode: testEventCode || dest.testCode,
        shopId: shop.id,
      });
      lastResult = res;
      if (res.success) anySuccess = true;
    }

    return NextResponse.json({
      success: anySuccess,
      eventId: finalEventId,
      eventsReceived: lastResult?.eventsReceived || 1,
      fbtraceId: lastResult?.fbtraceId,
      destinationsCount: destinations.length,
      error: lastResult?.error,
    });
  } catch (err) {
    return NextResponse.json(
      { success: false, error: err instanceof Error ? err.message : 'Internal Server Error' },
      { status: 500 }
    );
  }
}
