import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/db/client';
import { queueProducer } from '@/lib/queue/producer';
import { getAuthenticatedStore, unauthorizedResponse } from '@/lib/auth/storeContext';

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 events = await db.getCapiEvents(shop.id, 25);
    const auditLogs = await db.getAuditLogs(shop.id, 25);
    const jobs = queueProducer.getAllJobs(shop.id);

    return NextResponse.json({
      success: true,
      shop: {
        id: shop.id,
        domain: shop.shopify_domain,
        status: shop.status,
      },
      health: {
        shopifyAuth: shop.status === 'installed' ? 'healthy' : 'degraded',
        metaAuth: metaConn?.status === 'connected' ? 'healthy' : 'disconnected',
        capiStatus: events.some((e) => e.status === 'sent') ? 'healthy' : 'waiting_for_events',
        queueStatus: 'idle',
      },
      capiEvents: events,
      auditLogs,
      activeJobs: jobs.slice(-10),
    });
  } catch (err) {
    return NextResponse.json(
      { success: false, error: err instanceof Error ? err.message : 'Internal Server Error' },
      { status: 500 }
    );
  }
}
