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

export const POST = async (request: NextRequest) => {
  const middlewareResponse = await middleware(request);
  if (middlewareResponse) return middlewareResponse;
  try {
    const body = await request.json() as {
      message: Message;
    };
    const { message } = body;
    if (!message) {
      console.log('Message:', message);
      return NextResponse.json(
        { message: 'Missing message' }, { status: 400 }
      );
    }
    const newMessage: Message | null = await sendMessage(message);
    if (!newMessage) {
      return NextResponse.json(
        { message: 'Error sending message' }, { status: 500 }
      );
    }
    return NextResponse.json(newMessage);
  } catch (error) {
    console.error('Error sending message:', error);
    if (error instanceof Error) {
      return NextResponse.json(
        { message: error.message }, { status: 500 }
      );
    } else {
      return NextResponse.json(
        { message: 'Unknown error occurred' }, { status: 500 }
      );
    }
  }
};
