import { NextRequest, NextResponse } from 'next/server';
import { serverApiClient } from '@/utils/serverApiClient';

/**
 * POST /api/vision/invite-action
 * Accept or reject vision board invitations
 * Body: { order_id: string, action: 'accept' | 'reject' }
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { order_id, action, reason } = body;

    if (!order_id || !action) {
      return NextResponse.json(
        { message: 'Missing required fields: order_id and action' },
        { status: 400 }
      );
    }

    if (action !== 'accept' && action !== 'reject') {
      return NextResponse.json(
        { message: 'Invalid action. Must be "accept" or "reject"' },
        { status: 400 }
      );
    }

    const payload: Record<string, string> = { order_id };
    if (reason) payload.reason = reason;

    const response = await serverApiClient(`invite-vision/${action}`, {
      method: 'POST',
      body: JSON.stringify(payload),
      cache: 'no-store',
    });

    if (!response.success) {
      return NextResponse.json(
        { message: response.message || `Failed to ${action} invitation` },
        { status: 400 }
      );
    }

    return NextResponse.json({
      success: true,
      data: response.data,
      message: `Invite ${action}ed successfully`,
    });
  } catch (error: any) {
    console.error('Error handling invite action:', error);
    return NextResponse.json(
      { message: error.message || 'Internal server error' },
      { status: 500 }
    );
  }
}
