import { db } from '@/lib/db';
import { getSession } from '@/src/lib/auth';
import { createResponse, handleApiError } from '@/src/lib/api';

export async function DELETE(req: Request, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params;
    const session = await getSession();
    if (session?.user?.role !== 'ADMIN') {
      return createResponse(401, 'Unauthorized');
    }

    const user = await db.user.findUnique({ where: { id } });
    if (!user) {
      return createResponse(404, 'User not found');
    }

    if (user.role === 'ADMIN') {
      return createResponse(400, 'Cannot delete admin user');
    }
    await db.user.delete({ where: { id } });
    return createResponse(200, 'User deleted successfully', { data: user });
  } catch (error) {
    return handleApiError(error);
  }
}

export async function PATCH(req: Request, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params;
    const session = await getSession();
    if (session?.user?.role !== 'ADMIN' && session?.user?.id !== id) {
      return createResponse(401, 'Unauthorized');
    }
    const { role, vercelAccessToken } = await req.json();

    if (!role) {
      await db.user.update({
        where: { id },
        data: { vercelAccessToken },
      });
      return createResponse(200, 'User updated successfully');
    }

    await db.user.update({ where: { id }, data: { role } });
    return createResponse(200, 'User updated successfully');
  } catch (error) {
    return handleApiError(error);
  }
}
