import { db } from '@/db/client';
import { logger } from '@/lib/logger';
import { queueProducer } from '@/lib/queue/producer';

export async function handleShopifyWebhook(
  topic: string,
  shopDomain: string,
  webhookId: string,
  payload: Record<string, unknown>
): Promise<{ success: boolean; message: string }> {
  const shop = await db.getShopByDomain(shopDomain);
  if (!shop) {
    logger.warn(`Received webhook ${topic} for unregistered shop ${shopDomain}`);
    return { success: false, message: 'Shop not found' };
  }

  // 1. Record incoming webhook event
  const webhookRecord = await db.recordWebhook({
    id: `wh_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`,
    shop_id: shop.id,
    topic,
    shopify_webhook_id: webhookId || `wh_header_${Date.now()}`,
    payload_json: JSON.stringify(payload),
    status: 'queued',
    attempts: 0,
    created_at: new Date().toISOString(),
  });

  // 2. Queue background job to process webhook asynchronously
  await queueProducer.enqueue('webhook_process', shop.id, {
    webhook_event_id: webhookRecord.id,
    topic,
    body: payload,
  });

  logger.info(`Shopify webhook ${topic} enqueued for shop ${shopDomain}`);
  return { success: true, message: 'Webhook queued successfully' };
}
