'use server';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { updatePushToken } from '~/server/functions';
import { middleware } from '~/middleware';

export const POST = async (request: NextRequest) => {
  const middlewareResponse = await middleware(request);
  if (middlewareResponse) return middlewareResponse;
  try {
    const url = new URL(request.url);
    const userId = Number.parseInt(url.searchParams.get('userId') ?? '');
    const pushToken = url.searchParams.get('pushToken');
    if (!userId || !pushToken || isNaN(userId))
      return NextResponse.json(
        { message: 'Missing userId or pushToken' }, { status: 400 }
      );
    const result = await updatePushToken(userId, pushToken);
    if (!result) {
      return NextResponse.json(
        { message: 'Error updating push token' }, { status: 500 }
      );
    }
    return NextResponse.json(
      { message: 'Push token updated successfully' }, { status: 200 }
    );
  } catch (error) {
    console.error('Error updating push token:', error);
    if (error instanceof Error) {
      return NextResponse.json(
        { message: error.message }, { status: 500 }
      );
    } else {
      return NextResponse.json(
        { message: 'Unknown error occurred' }, { status: 500 }
      );
    }
  }
};
