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

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

    return NextResponse.json(
      {
        success: true,
        message: 'User permission override created successfully',
        override_id: overrideId
      },
      { status: 201 }
    );
  } 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 create permission override' }, { status: 500 });
  }
}
