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

export const POST = async (request: NextRequest) => {
  const middlewareResponse = await middleware(request);
  if (middlewareResponse) return middlewareResponse;

  try {
    // Parse the request body
    const body = await request.json() as {
      appleId: string;
      email: string;
      fullName: string;
      pushToken: string;
    };
    const { appleId, email, fullName, pushToken } = body;

    // Validate the required fields
    if (!appleId || !email || !fullName || !pushToken) {
      return NextResponse.json(
        { message: 'Missing required parameters' },
        { status: 400 }
      );
    }

    // Create the new user
    const newUser: User | undefined = await createUser(appleId, email, fullName, pushToken);

    if (!newUser) {
      return NextResponse.json(
        { message: 'Error creating user' },
        { status: 500 }
      );
    }

    // Return the new user data
    return NextResponse.json(newUser);

  } catch (error) {
    console.error('Error creating user:', error);
    if (error instanceof Error) {
      return NextResponse.json({ message: error.message }, { status: 500 });
    } else {
      return NextResponse.json({ message: 'Unknown error occurred' }, { status: 500 });
    }
  }
};
