'use server';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getMessages } from '~/server/functions';
import { middleware } from '~/middleware';
import type { Message } 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 limit = Number.parseInt(url.searchParams.get('limit') ?? '');
    const offset = Number.parseInt(url.searchParams.get('offset') ?? '0');
    if (!userId || isNaN(userId) || !limit || isNaN(limit) || isNaN(offset)) {
      console.log('userId: ', userId, 'limit: ', limit, 'offset: ', offset);
      return NextResponse.json(
        { message: 'Missing userId, limit, or offset' }, { status: 400 }
      );
    }
    const messages: Message[] | undefined = await getMessages(userId, limit, offset);
    if (messages === undefined) {
      return NextResponse.json(
        { message: 'No messages found' }, { status: 404 }
      );
    }
    return NextResponse.json(messages);
  } catch (error) {
    console.error('Error getting messages:', error);
    if (error instanceof Error) {
      return NextResponse.json(
        { message: error.message }, { status: 500 }
      );
    } else {
      return NextResponse.json(
        { message: 'Unknown error occurred' }, { status: 500 }
      );
    }
  }
};
