import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/db/client';
import { getAuthenticatedStore, unauthorizedResponse } from '@/lib/auth/storeContext';
import { canUseFeature } from '@/lib/shopify/plan-capability';

export const dynamic = 'force-dynamic';

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

    const audiences = await db.getAudiencesByShopId(shop.id);

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

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

    // Feature gating: Meta Audiences Sync (Lookalikes & Retargeting) is Scale Plan only
    if (!canUseFeature(shop.plan, 'meta.meta_audiences_sync')) {
      return NextResponse.json(
        {
          success: false,
          code: 'FEATURE_NOT_AVAILABLE',
          error: 'Meta Audiences Sync (Lookalikes & Retargeting) is exclusive to the Scale Plan. Please upgrade your subscription to sync custom audience segments with Meta.',
          upgradeUrl: '/meta-connector/pricing',
        },
        { status: 403 }
      );
    }

    const body = await req.json();
    const { name, type, rule } = body;

    const newAudience = {
      id: `aud_meta_${Date.now()}`,
      shop_id: shop.id,
      name: name || 'Custom Segment',
      type: type || 'Custom Customer List',
      rule: rule || 'All active customers',
      size: 0,
      matchRate: '—',
      lastSynced: 'Pending sync',
      status: 'READY',
    };

    await db.createAudience(newAudience);

    return NextResponse.json({
      success: true,
      audience: newAudience,
    });
  } catch (err) {
    return NextResponse.json(
      { success: false, error: err instanceof Error ? err.message : 'Failed to create audience' },
      { status: 500 }
    );
  }
}
