import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/db/client';
import { decrypt } from '@/lib/crypto/encryption';
import { MetaGraphClient } from '@/lib/meta/client';
import { getAuthenticatedStore } from '@/lib/auth/storeContext';

export const dynamic = 'force-dynamic';

export async function GET(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url);
    const shopDomain = searchParams.get('shop') || searchParams.get('shopify_domain');
    const businessId = searchParams.get('businessId');
    const connectedOnly = searchParams.get('connectedOnly') === 'true';

    let shop = await getAuthenticatedStore(req);
    if (!shop && shopDomain) {
      shop = await db.getShopByDomain(shopDomain);
    }
    if (!shop) {
      return NextResponse.json({
        success: true,
        connected: false,
        user: null,
        businesses: [],
        selectedBusinessId: '',
        pixels: [],
        catalogs: [],
        accessTokenMasked: '',
        rawToken: '',
      });
    }

    const metaConn = await db.getMetaConnectionByShopId(shop.id);

    // Strictly verify real connection
    if (!metaConn || metaConn.status !== 'connected' || !metaConn.access_token_encrypted) {
      return NextResponse.json({
        success: true,
        connected: false,
        user: null,
        businesses: [],
        selectedBusinessId: '',
        pixels: [],
        catalogs: [],
        accessTokenMasked: '',
        rawToken: '',
      });
    }

    let accessToken = '';
    try {
      accessToken = decrypt(metaConn.access_token_encrypted);
    } catch {
      accessToken = '';
    }

    if (!accessToken) {
      return NextResponse.json({
        success: true,
        connected: false,
        user: null,
        businesses: [],
        selectedBusinessId: '',
        pixels: [],
        catalogs: [],
        accessTokenMasked: '',
        rawToken: '',
      });
    }

    const graphClient = new MetaGraphClient(accessToken);

    // Fetch user profile
    let user = null;
    try {
      user = await graphClient.getUserProfile();
    } catch {
      user = {
        id: metaConn.fb_user_id || metaConn.business_id || '',
        name: metaConn.fb_user_name || metaConn.business_name || 'Facebook User',
        avatar: metaConn.fb_user_id ? `https://graph.facebook.com/${metaConn.fb_user_id}/picture?type=large` : null,
      };
    }

    // Fetch real Meta Businesses accessible by this token
    let businesses: Array<{ id: string; name: string }> = [];
    try {
      businesses = await graphClient.getBusinesses();
    } catch {
      businesses = [];
    }

    if (businesses.length === 0 && metaConn.business_id) {
      businesses.push({
        id: metaConn.business_id,
        name: metaConn.business_name || `Business Portfolio (${metaConn.business_id})`,
      });
    }

    const targetBizId = businessId || metaConn.business_id || businesses[0]?.id || '';

    // 2. Fetch all pixels configured/connected in the database for this shop
    const dbPixels = await db.getPixelsByShopId(shop.id);
    const connectedPixels = dbPixels.map((p) => {
      const rawName = p.pixel_name || 'Pixel';
      const cleanName = rawName.includes(p.pixel_id) ? rawName : `${p.pixel_id} - ${rawName}`;
      return {
        id: p.pixel_id,
        name: cleanName,
        source: p.source || (p.facebook_account_id ? 'auto' : 'manual'),
        is_active: p.is_active !== false,
        verification_status: p.verification_status || 'verified',
      };
    });

    let pixels: Array<{ id: string; name: string; source: string; is_active: boolean; verification_status: string }> = [];

    if (connectedOnly) {
      // Strictly return only pixels connected to this store in the app
      pixels = connectedPixels;
    } else {
      // Retrieve all available pixels: Live Meta Graph API Datasets/Pixels + Locally configured pixels
      const pixelsMap = new Map<string, { id: string; name: string; source: string; is_active: boolean; verification_status: string }>();

      // 1. Fetch real Pixels & Datasets from Meta Graph API for the selected Business
      if (targetBizId) {
        try {
          const fbPixels = await graphClient.getPixels(targetBizId);
          fbPixels.forEach((fp) => {
            pixelsMap.set(fp.id, {
              id: fp.id,
              name: fp.name,
              source: 'auto',
              is_active: true,
              verification_status: 'verified',
            });
          });
        } catch (err) {
          console.error('Failed to fetch pixels from Meta Graph API:', err);
        }
      }

      // 2. Also merge with pixels stored in the database so all store and manual pixels appear
      dbPixels.forEach((p) => {
        if (!pixelsMap.has(p.pixel_id)) {
          pixelsMap.set(p.pixel_id, {
            id: p.pixel_id,
            name: `${p.pixel_id} - ${p.pixel_name || 'Pixel'}`,
            source: p.source || (p.facebook_account_id ? 'auto' : 'manual'),
            is_active: p.is_active !== false,
            verification_status: p.verification_status || 'unverified',
          });
        }
      });

      pixels = Array.from(pixelsMap.values());
    }

    // Retrieve catalogs belonging to this store and connected Facebook account
    const dbCatalogs = await db.getCatalogs(shop.id, metaConn.fb_user_id || null);
    const catalogs = dbCatalogs.map((c) => ({
      id: c.fb_catalog_id,
      name: c.name,
      product_count: c.product_count,
    }));

    const masked = accessToken.length > 8
      ? `${accessToken.slice(0, 4)}••••••••••••${accessToken.slice(-4)}`
      : '••••••••••••';

    return NextResponse.json({
      success: true,
      connected: true,
      user,
      businesses,
      selectedBusinessId: targetBizId,
      pixels,
      connectedPixels,
      catalogs,
      accessTokenMasked: masked,
      rawToken: accessToken,
    });
  } catch (err) {
    return NextResponse.json(
      { success: false, error: err instanceof Error ? err.message : 'Failed to query Meta Graph API' },
      { status: 500 }
    );
  }
}
