import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/db/client';
import { getAuthenticatedStore, unauthorizedResponse } from '@/lib/auth/storeContext';
import { META_CONFIG } from '@/config/meta';

export const dynamic = 'force-dynamic';

export async function GET(req: NextRequest) {
  try {
    const shop = await getAuthenticatedStore(req);
    if (!shop) {
      return unauthorizedResponse();
    }

    const metaConn = await db.getMetaConnectionByShopId(shop.id);
    const pixels = await db.getPixelsByShopId(shop.id);
    const activePixel = pixels.find((p) => p.is_active) || pixels[0];
    const capiEvents = await db.getCapiEvents(shop.id, 100);
    const metaEventsToday = capiEvents.filter((e) => e.status === 'sent').length;

    const channels = [
      {
        id: 'meta',
        name: 'Meta (Facebook & Instagram)',
        iconBg: 'bg-blue-600',
        textColor: 'text-white',
        badge: `Multi-Pixel & CAPI ${META_CONFIG.graphVersion}`,
        enabled: Boolean(activePixel || metaConn),
        pixelId: activePixel ? activePixel.pixel_id : (metaConn?.pixel_id || ''),
        apiToken: metaConn?.access_token_encrypted ? '••••••••••••••••••••••••••••••••' : '',
        testCode: activePixel?.test_event_code || metaConn?.test_event_code || '',
        status: (activePixel || metaConn) ? 'ACTIVE' : 'NOT_CONFIGURED',
        eventsToday: metaEventsToday,
      },
      {
        id: 'tiktok',
        name: 'TikTok Pixel & Events API',
        iconBg: 'bg-black',
        textColor: 'text-white',
        badge: 'Server Events API v1.3',
        enabled: false,
        pixelId: '',
        apiToken: '',
        testCode: '',
        status: 'NOT_CONFIGURED',
        eventsToday: 0,
      },
      {
        id: 'google',
        name: 'Google Ads & GA4 Enhanced Conversions',
        iconBg: 'bg-amber-500',
        textColor: 'text-white',
        badge: 'Measurement Protocol & GTM',
        enabled: false,
        pixelId: '',
        apiToken: '',
        testCode: '',
        status: 'NOT_CONFIGURED',
        eventsToday: 0,
      },
      {
        id: 'pinterest',
        name: 'Pinterest Tag & API for Conversions',
        iconBg: 'bg-rose-600',
        textColor: 'text-white',
        badge: 'Conversions API v5',
        enabled: false,
        pixelId: '',
        apiToken: '',
        testCode: '',
        status: 'NOT_CONFIGURED',
        eventsToday: 0,
      },
      {
        id: 'snapchat',
        name: 'Snapchat Conversions API (CAPI)',
        iconBg: 'bg-yellow-400',
        textColor: 'text-black',
        badge: 'Snap Business API v3',
        enabled: false,
        pixelId: '',
        apiToken: '',
        testCode: '',
        status: 'NOT_CONFIGURED',
        eventsToday: 0,
      },
    ];

    return NextResponse.json({
      success: true,
      shopDomain: shop.shopify_domain,
      channels,
    });
  } catch (err) {
    return NextResponse.json(
      { success: false, error: err instanceof Error ? err.message : 'Failed to fetch multichannel settings' },
      { status: 500 }
    );
  }
}

export async function POST(req: NextRequest) {
  try {
    const shop = await getAuthenticatedStore(req);
    if (!shop) {
      return unauthorizedResponse();
    }

    const body = await req.json();
    const { channelId, pixelId, apiToken, testCode, enabled } = body;

    return NextResponse.json({
      success: true,
      message: `Channel ${channelId} settings updated successfully for ${shop.shopify_domain}`,
    });
  } catch (err) {
    return NextResponse.json(
      { success: false, error: err instanceof Error ? err.message : 'Failed to save channel' },
      { status: 500 }
    );
  }
}
