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

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') || 'customers/redact';
    const shopDomain = req.headers.get('x-shopify-shop-domain') || '';

    const isLocalDev = process.env.NODE_ENV !== 'production' || process.env.SHOPIFY_API_SECRET?.startsWith('mock_');
    if (!isLocalDev) {
      const isValid = verifyShopifyWebhookHmac(rawBody, hmacHeader);
      if (!isValid) {
        return new NextResponse('Unauthorized: Invalid HMAC signature', { status: 401 });
      }
    }

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

    logger.info(`Processing mandatory GDPR webhook: ${topic} for shop ${shopDomain}`, { payload });

    const shop = await db.getShopByDomain(shopDomain);
    if (shop) {
      await db.recordAuditLog({
        id: `audit_gdpr_${Date.now()}`,
        shop_id: shop.id,
        action: `gdpr_${topic.replace('/', '_')}`,
        actor: 'shopify_webhook',
        metadata: { topic, shopDomain },
        created_at: new Date().toISOString(),
      });
    }

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