'use server';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getInitialDataByAppleId } from '~/server/functions';
import { middleware } from '~/middleware';
import type { InitialData } 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 appleId = url.searchParams.get('appleId');
    if (!appleId)
      return NextResponse.json({ message: 'Missing appleId' }, { status: 400 });
    const initialData: InitialData | null = await getInitialDataByAppleId(appleId);
    if (!initialData) {
      return NextResponse.json({ message: 'No initial data found' }, { status: 404 });
    }
    return NextResponse.json(initialData);
  } catch (error) {
    console.error('Error parsing request:', error);
    return NextResponse.json({ message: 'Invalid request' }, { status: 400 });
  }
};
