'use server';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { checkRelationshipStatus } from '~/server/functions';
import { middleware } from '~/middleware';
import type { RelationshipData } 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') ?? '');
    if (!userId || isNaN(userId))
      return NextResponse.json(
        { message: 'Missing userId' }, { status: 400 }
      );
    const relationshipData: RelationshipData | null = await checkRelationshipStatus(userId);
    if (!relationshipData) {
      return NextResponse.json(
        { message: 'No relationship data found' }, { status: 404 }
      );
    }
    return NextResponse.json(relationshipData);
  } catch (error) {
    console.error('Error checking 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 }
      );
    }
  }
};
