import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/db/client';

export const dynamic = 'force-dynamic';

export async function GET(req: NextRequest) {
  try {
    const allShops = await db.getAllShops().catch(() => []);
    const notifications: Array<{
      id: string;
      type: string;
      title: string;
      message: string;
      time: string;
      read: boolean;
      severity: string;
    }> = [];

    for (const shop of allShops) {
      const displayName = shop.shop_name || shop.shopify_domain;
      if (shop.status === 'installed') {
        notifications.push({
          id: `notif_install_${shop.id}`,
          type: 'install',
          title: 'Store Installed',
          message: `${displayName} (${shop.shopify_domain}) is active on the ${shop.plan || 'growth'} tier.`,
          time: 'Active',
          read: true,
          severity: 'info',
        });
      } else if (shop.status === 'uninstalled') {
        notifications.push({
          id: `notif_uninstall_${shop.id}`,
          type: 'uninstall',
          title: 'Store Uninstalled',
          message: `${displayName} uninstalled the app.`,
          time: 'Recently',
          read: false,
          severity: 'warning',
        });
      }
    }

    return NextResponse.json({
      success: true,
      unreadCount: notifications.filter((n) => !n.read).length,
      notifications,
    });
  } catch (err: any) {
    return NextResponse.json({
      success: true,
      unreadCount: 0,
      notifications: [],
    });
  }
}
