import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/db/client';
import { getAuthenticatedStore, unauthorizedResponse } from '@/lib/auth/storeContext';
import { decrypt } from '@/lib/crypto/encryption';
import { MetaCatalogService } from '@/lib/meta/catalog-service';

export const dynamic = 'force-dynamic';

export async function PATCH(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const shop = await getAuthenticatedStore(req);
    if (!shop) {
      return unauthorizedResponse();
    }
    const catalogId = params.id;
    if (!catalogId) {
      return NextResponse.json({ success: false, error: 'Invalid catalog ID' }, { status: 400 });
    }

    const catalog = await db.getCatalogById(catalogId);
    if (!catalog || catalog.shop_id !== shop.id) {
      return NextResponse.json({ success: false, error: 'Catalog not found' }, { status: 404 });
    }

    const body = await req.json().catch(() => ({}));
    const newPixelState = body.pixel_tracking !== undefined
      ? !!body.pixel_tracking
      : !catalog.pixel_tracking;

    // Resolve Meta access token
    const metaConn = await db.getMetaConnectionByShopId(shop.id);
    let accessToken = process.env.META_SYSTEM_ACCESS_TOKEN || '';
    if (!accessToken && metaConn?.access_token_encrypted && metaConn.status === 'connected') {
      try {
        accessToken = decrypt(metaConn.access_token_encrypted);
      } catch {
        accessToken = '';
      }
    }

    if (accessToken && catalog.fb_catalog_id && catalog.fb_pixel_id) {
      if (newPixelState) {
        await MetaCatalogService.linkPixel(catalog.fb_catalog_id, catalog.fb_pixel_id, accessToken);
      } else {
        await MetaCatalogService.unlinkPixel(catalog.fb_catalog_id, catalog.fb_pixel_id, accessToken);
      }
    }

    const nowIso = new Date().toISOString();
    await db.updateCatalog(catalogId, {
      pixel_tracking: newPixelState,
      updated_at: nowIso,
    });

    const updated = await db.getCatalogById(catalogId);

    return NextResponse.json({
      success: true,
      catalog: updated,
    });
  } catch (err: any) {
    console.error('[API /api/catalogs/[id]/pixel PATCH] Error:', err);
    return NextResponse.json(
      { success: false, error: err.message || 'Failed to toggle pixel tracking' },
      { status: 500 }
    );
  }
}
