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

export const GET = 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 searchTerm = url.searchParams.get('searchTerm');
    console.log(userId, searchTerm);
    if (!userId || !searchTerm || isNaN(userId))
      return NextResponse.json(
        { message: 'Missing userId or searchTerm' }, { status: 400 }
      );
    const users: User[] | undefined = await searchUsers(userId, searchTerm);
    if (users === undefined) {
      return NextResponse.json(
        { message: 'No users found' }, { status: 404 }
      );
    }
    return NextResponse.json(users);
  } catch (error) {
    console.error('Error searching users:', error);
    if (error instanceof Error) {
      return NextResponse.json(
        { message: error.message }, { status: 500 }
      );
    } else {
      return NextResponse.json(
        { message: 'Unknown error occurred' }, { status: 500 }
      );
    }
  }
};
