import { NextRequest, NextResponse } from 'next/server';
import { userPermissionAssignmentSchema } from '@/features/permission-management/schemas/user-permission-assignment';
import { saveUserPermissionAssignmentForOrganization } from '@/features/permission-management/server/user-permission-data';
import { AuthError, requireSuperAdminOrganizationAccess } from '@/lib/auth/session';

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ userId: string }> }
) {
  try {
    const { organization, session } = await requireSuperAdminOrganizationAccess();
    const body = userPermissionAssignmentSchema.parse(await request.json());
    await saveUserPermissionAssignmentForOrganization({
      organizationId: organization.id,
      actorUserId: session.user.id,
      userId: (await params).userId,
      payload: body
    });

    return NextResponse.json({
      success: true,
      message: 'User permission assignment saved successfully'
    });
  } 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 save user permission assignment' }, { status: 500 });
  }
}
