import { NextRequest, NextResponse } from 'next/server';
import { requirePermission } from '@/shared/admin/guards';
import { PERMISSIONS } from '@/shared/admin/permissions';
import { startImpersonation, stopImpersonation, getActiveImpersonation } from '@/shared/admin/impersonation';
import { requireAuth } from '@/shared/auth/guards';

// --- ASA GENERATED START ---
// Route handler for admin/impersonation slice.
// POST: start impersonation, DELETE: stop, GET: check active session.
// Security: requires admin.impersonate permission (server-side).
// --- ASA GENERATED END ---

// --- USER CODE START ---

export async function POST(request: NextRequest): Promise<NextResponse> {
  const { user, response } = await requirePermission(request, PERMISSIONS.IMPERSONATE);
  if (response) return response;

  const body = await request.json();
  const { subject_user_id, reason } = body;

  if (!subject_user_id || !reason) {
    return NextResponse.json(
      { success: false, error: 'subject_user_id and reason are required' },
      { status: 400 },
    );
  }

  const result = await startImpersonation(
    user!.id,
    user!.email,
    subject_user_id,
    reason,
  );

  if (result.error) {
    return NextResponse.json({ success: false, error: result.error }, { status: 400 });
  }

  return NextResponse.json({ success: true, session: result.session });
}

export async function DELETE(request: NextRequest): Promise<NextResponse> {
  const { user, response } = await requireAuth(request);
  if (response) return response;

  const result = await stopImpersonation(user!.id, user!.email);

  if (result.error) {
    return NextResponse.json({ success: false, error: result.error }, { status: 400 });
  }

  return NextResponse.json({ success: true });
}

export async function GET(): Promise<NextResponse> {
  const session = await getActiveImpersonation();
  return NextResponse.json({ active: !!session, session });
}

// --- USER CODE END ---
