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

/**
 * POST /api/vision/invite-submit
 * Share vision board with another user via email
 * Body: { email: string, session_id: string, customer_name: string }
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { email, session_id, customer_name, external_id } = body;

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

    // Email validation
    if (!email.includes('@')) {
      return NextResponse.json(
        { message: 'Invalid email address' },
        { status: 400 }
      );
    }

    const query: Record<string, string> = {
      email,
      session_id,
      customer_name: customer_name || '',
    };
    if (external_id) query.external_id = external_id;

    const response = await serverApiClient('co-creation/invite', {
      method: 'GET',
      query,
      cache: 'no-store',
    });

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

    return NextResponse.json({
      success: true,
      data: response.data,
      message: 'Vision board shared successfully',
    });
  } catch (error: any) {
    console.error('Error sending invite:', error);
    return NextResponse.json(
      { message: error.message || 'Internal server error' },
      { status: 500 }
    );
  }
}
