import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/db/client';
import { getAuthenticatedStore, unauthorizedResponse } from '@/lib/auth/storeContext';
import { syncCatalog } from '@/lib/sync/catalog-sync-service';

export const dynamic = 'force-dynamic';

export async function POST(
  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 metaConn = await db.getMetaConnectionByShopId(shop.id);
    if (!metaConn || metaConn.status !== 'connected' || !metaConn.access_token_encrypted) {
      return NextResponse.json(
        { success: false, error: 'Facebook account not connected' },
        { status: 403 }
      );
    }

    const result = await syncCatalog(catalogId);

    return NextResponse.json({
      success: result.success,
      result,
      error: result.error,
    });
  } catch (err: any) {
    console.error('[API /api/catalogs/[id]/sync POST] Error:', err);
    return NextResponse.json(
      { success: false, error: err.message || 'Sync operation failed' },
      { status: 500 }
    );
  }
}
