'use server';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { createRelationshipRequest } 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;
      targetUserId: number;
    };
    const { userId, targetUserId } = body;
    console.log('User ID:', userId, 'Partner ID:', targetUserId);
    if (!userId || !targetUserId || isNaN(userId) || isNaN(targetUserId))
      return NextResponse.json(
        { message: 'Missing userId or targetUserId' }, { status: 400 }
      );
    const relationshipData: RelationshipData | null = await createRelationshipRequest(userId, targetUserId);
    if (!relationshipData) {
      return NextResponse.json(
        { message: 'Error creating relationship request' }, { status: 500 }
      );
    }
    return NextResponse.json(relationshipData);
  } catch (error) {
    console.error('Error creating relationship request:', error);
    if (error instanceof Error) {
      return NextResponse.json(
        { message: error.message }, { status: 500 }
      );
    } else {
      return NextResponse.json(
        { message: 'Unknown error occurred' }, { status: 500 }
      );
    }
  }
};
