import { type NextRequest, NextResponse } from 'next/server';
import { ForbiddenError, requireGuildAccess, toApiErrorResponse } from '@/lib/auth';
import { writeDashboardAudit } from '@/lib/audit';
import { fetchDiscordUserGuildsCached } from '@/lib/discord-oauth';
import { enqueueGuildBackupRestore, getGuildBackupRecord } from '@/lib/module-configs/guildbackup';
import { prisma } from '@/lib/prisma';

interface RouteParams {
  params: Promise<{ guildId: string; backupId: string }>;
}

/**
 * Restore is intentionally restricted to the Discord server owner, per SPEC
 * ("Restore nur durch Server-Owner mit doppelter Bestätigung"). The double
 * confirmation itself happens client-side before this request is sent.
 */
export async function POST(_request: NextRequest, { params }: RouteParams) {
  const { guildId, backupId } = await params;
  try {
    const session = await requireGuildAccess(guildId);

    const guilds = await fetchDiscordUserGuildsCached(session.accessToken);
    const guild = guilds.find((entry) => entry.id === guildId);
    if (!guild?.owner) {
      throw new ForbiddenError('Only the Discord server owner can restore a backup');
    }

    const backup = await getGuildBackupRecord(guildId, backupId);
    if (!backup) {
      return NextResponse.json({ error: 'Backup not found' }, { status: 404 });
    }

    await enqueueGuildBackupRestore(backupId, guildId, session.user.id);

    await writeDashboardAudit(prisma, {
      guildId,
      actorUserId: session.user.id,
      action: 'guildbackup.restore',
      path: `/dashboard/${guildId}/backup`,
      after: { backupId }
    });

    return NextResponse.json({ ok: true, queued: true });
  } catch (error) {
    return toApiErrorResponse(error);
  }
}
