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

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

    return NextResponse.json({
      success: true,
      message: 'User permission override updated 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 update permission override' }, { status: 500 });
  }
}

export async function DELETE(
  _: NextRequest,
  { params }: { params: Promise<{ userId: string; overrideId: string }> }
) {
  try {
    const { organization, session } = await requireSuperAdminOrganizationAccess();
    const routeParams = await params;
    await deleteUserPermissionOverrideForOrganization({
      organizationId: organization.id,
      actorUserId: session.user.id,
      userId: routeParams.userId,
      overrideId: Number(routeParams.overrideId)
    });

    return NextResponse.json({
      success: true,
      message: 'User permission override removed 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 remove permission override' }, { status: 500 });
  }
}
