import { NextResponse } from 'next/server';
import { toApiErrorResponse } from '@/lib/auth';
import { getAllQueueStats, retryFailedJobs } from '@/lib/owner-jobs';
import { writeOwnerAudit } from '@/lib/owner-audit';
import { requireOwner } from '@/lib/owner-auth';
import { prisma } from '@/lib/prisma';

export async function GET() {
  try {
    await requireOwner('SUPPORT');
    const [queues, migrations] = await Promise.all([
      getAllQueueStats(),
      prisma.$queryRaw<Array<{ migration_name: string; finished_at: Date | null }>>`
        SELECT migration_name, finished_at FROM "_prisma_migrations" ORDER BY finished_at DESC NULLS LAST
      `
    ]);
    return NextResponse.json({
      queues,
      migrations: migrations.map((row) => ({
        name: row.migration_name,
        finishedAt: row.finished_at?.toISOString() ?? null
      }))
    });
  } catch (error) {
    return toApiErrorResponse(error);
  }
}

export async function POST(request: Request) {
  try {
    const session = await requireOwner('ADMIN');
    const body = (await request.json()) as { queueName?: string };
    if (!body.queueName) {
      return NextResponse.json({ error: 'queueName required' }, { status: 400 });
    }
    const retried = await retryFailedJobs(body.queueName);
    await writeOwnerAudit(prisma, {
      actorUserId: session.user.id,
      action: 'jobs.retryFailed',
      targetType: 'Queue',
      targetId: body.queueName,
      after: { retried }
    });
    return NextResponse.json({ retried });
  } catch (error) {
    return toApiErrorResponse(error);
  }
}
