import { NextResponse } from 'next/server';
import { resendNotification } from '@/features/foundation/notifications/server/service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

export async function POST(
  _request: Request,
  context: { params: Promise<{ id: string }> },
) {
  try {
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.notificationResend,
    });
    const { id } = await context.params;
    const dispatch = await resendNotification({
      organizationId: organization.id,
      actorUserId: session.user.id,
      dispatchId: id,
    });

    return NextResponse.json({
      message: 'Notification resent successfully',
      dispatch,
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    if (error instanceof Error) {
      return NextResponse.json({ message: error.message }, { status: 400 });
    }

    return NextResponse.json({ message: 'Unable to resend notification' }, { status: 500 });
  }
}
