'use server';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { updateRelationshipStatus } from '~/server/functions';
import { middleware } from '~/middleware';
import type { RelationshipData } 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 {
      userId: number;
      status: string;
    };
    const { userId, status } = body;
    console.log('User ID:', userId, 'Status:', status);
    if (!userId || !status || isNaN(userId))
      return NextResponse.json(
        { message: 'Missing userId or status' }, { status: 400 }
      );
    const theStatus = status === 'accepted' ? 'accepted' : 'rejected';
    const relationshipData: RelationshipData | null | undefined =
      await updateRelationshipStatus(userId, theStatus);
    if (!relationshipData || relationshipData === undefined) {
      return NextResponse.json(
        { message: 'Error updating relationship status.' }, { status: 500 }
      );
    }
    return NextResponse.json(relationshipData);
  } catch (error) {
    console.error('Error updating relationship status:', error);
    if (error instanceof Error) {
      return NextResponse.json(
        { message: error.message }, { status: 500 }
      );
    } else {
      return NextResponse.json(
        { message: 'Unknown error occurred' }, { status: 500 }
      );
    }
  }
};
