import { NextRequest, NextResponse } from 'next/server';
import { count, desc, eq, inArray } from 'drizzle-orm';
import { db } from '@/lib/db/client';
import { campaigns, emailQueue, recipients } from '@/lib/db/schema';
import { withAuth } from '@/core/auth';
import { isModuleEnabled } from '@/core/modules';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

/**
 * Sende-Warteschlange: letzte `email_queue`-Jobs der zugänglichen Workspaces.
 * Nur wenn das Modul `sending` aktiv ist (sonst 404 wie andere Sending-Routen).
 */
export const GET = withAuth(async (req: NextRequest, ctx) => {
  if (!isModuleEnabled('sending')) {
    return NextResponse.json({ error: 'Sending module is not enabled.' }, { status: 404 });
  }

  if (ctx.workspaceIds.length === 0) {
    return NextResponse.json({ jobs: [], countsByStatus: {}, limit: 0 });
  }

  const limitParam = req.nextUrl.searchParams.get('limit');
  const limit = Math.min(500, Math.max(1, Number(limitParam) || 200));

  const statusCounts = db
    .select({
      status: emailQueue.status,
      count: count(),
    })
    .from(emailQueue)
    .innerJoin(campaigns, eq(emailQueue.campaignId, campaigns.id))
    .where(inArray(campaigns.workspaceId, ctx.workspaceIds))
    .groupBy(emailQueue.status)
    .all();

  const countsByStatus: Record<string, number> = {};
  for (const row of statusCounts) {
    countsByStatus[row.status] = row.count;
  }

  const jobs = db
    .select({
      id: emailQueue.id,
      status: emailQueue.status,
      attempts: emailQueue.attempts,
      lastError: emailQueue.lastError,
      messageId: emailQueue.messageId,
      scheduledAt: emailQueue.scheduledAt,
      createdAt: emailQueue.createdAt,
      sentAt: emailQueue.sentAt,
      campaignId: emailQueue.campaignId,
      campaignName: campaigns.name,
      recipientEmail: recipients.email,
    })
    .from(emailQueue)
    .innerJoin(campaigns, eq(emailQueue.campaignId, campaigns.id))
    .innerJoin(recipients, eq(emailQueue.recipientId, recipients.id))
    .where(inArray(campaigns.workspaceId, ctx.workspaceIds))
    .orderBy(desc(emailQueue.createdAt))
    .limit(limit)
    .all();

  return NextResponse.json({
    jobs: jobs.map((j) => ({
      ...j,
      scheduledAt: j.scheduledAt.toISOString(),
      createdAt: j.createdAt.toISOString(),
      sentAt: j.sentAt?.toISOString() ?? null,
    })),
    countsByStatus,
    limit,
  });
});
