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 POST(req: NextRequest) {
  try {
    const shop = await getAuthenticatedStore(req);
    if (!shop) {
      return unauthorizedResponse();
    }

    const body = await req.json().catch(() => ({}));
    const {
      eventName = 'Purchase',
      testEventCode,
      value = 49.99,
      currency = 'USD',
    } = body;

    const metaConn = await db.getMetaConnectionByShopId(shop.id);
    if (!metaConn || !metaConn.pixel_id) {
      return NextResponse.json(
        { success: false, error: `Meta Pixel is not connected for store ${shop.shopify_domain}. Please configure your Meta Pixel in Settings.` },
        { status: 400 }
      );
    }

    const metaToken = decrypt(metaConn.access_token_encrypted);
    const codeToUse = testEventCode || metaConn.test_event_code || 'TEST12345';

    const normalizedUser = normalizeUserData({
      email: `test.${shop.id}@example.com`,
      phone: '+15551234567',
      firstName: 'Test',
      lastName: 'Customer',
      city: 'New York',
      country: 'US',
      zip: '10001',
      clientIp: '198.51.100.1',
      userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
    });

    const eventId = generateEventId('test_evt');

    const event: MetaServerEvent = {
      event_name: eventName,
      event_time: Math.floor(Date.now() / 1000),
      event_id: eventId,
      event_source_url: `https://${shop.shopify_domain}/checkout/test`,
      action_source: 'website',
      user_data: normalizedUser,
      custom_data: {
        currency,
        value: Number(value),
        content_ids: [`${shop.id}_test_prod`],
        content_type: 'product',
      },
    };

    const result = await sendMetaCapiEvents({
      pixelId: metaConn.pixel_id,
      accessToken: metaToken,
      events: [event],
      testEventCode: codeToUse,
      shopId: shop.id,
    });

    return NextResponse.json({
      success: result.success,
      eventId,
      pixelId: metaConn.pixel_id,
      testEventCode: codeToUse,
      fbtraceId: result.fbtraceId,
      eventsReceived: result.eventsReceived,
      message: result.success ? `Test event successfully delivered to Meta Events Manager for ${shop.shopify_domain}` : result.error,
    });
  } catch (err) {
    return NextResponse.json(
      { success: false, error: err instanceof Error ? err.message : 'Internal Server Error' },
      { status: 500 }
    );
  }
}
