import { NextRequest, NextResponse } from 'next/server';
import { verifyShopifyWebhookHmac } from '@/lib/shopify/hmac';
import { handleShopifyWebhook } from '@/lib/shopify/webhooks';
import { logger } from '@/lib/logger';

export const dynamic = 'force-dynamic';

export async function POST(req: NextRequest) {
  try {
    const rawBody = await req.text();
    const hmacHeader = req.headers.get('x-shopify-hmac-sha256') || '';
    const topic = req.headers.get('x-shopify-topic') || 'unknown';
    const shopDomain = req.headers.get('x-shopify-shop-domain') || '';
    const webhookId = req.headers.get('x-shopify-webhook-id') || '';

    // Verify HMAC signature in production environments
    const isLocalDev = process.env.NODE_ENV !== 'production' || process.env.SHOPIFY_API_SECRET?.startsWith('mock_');
    if (!isLocalDev) {
      const isValid = verifyShopifyWebhookHmac(rawBody, hmacHeader);
      if (!isValid) {
        logger.warn(`Rejected invalid Shopify webhook HMAC signature for topic: ${topic}`);
        return new NextResponse('Unauthorized: Invalid HMAC signature', { status: 401 });
      }
    }

    let payload: Record<string, unknown> = {};
    try {
      payload = JSON.parse(rawBody);
    } catch {
      payload = {};
    }

    // Immediately enqueue and respond with 200 OK
    await handleShopifyWebhook(topic, shopDomain, webhookId, payload);

    return new NextResponse('Webhook Received', { status: 200 });
  } catch (err) {
    logger.error('Error handling Shopify webhook', err);
    return new NextResponse('Internal Server Error', { status: 500 });
  }
}
