import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';

const API_BASE_URL = process.env.API_BASE_URL || "https://admin.mymorni.com/api/v1";



export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const { name, email, password, password_confirmation, marketing_consent, roleSelected, captchaToken } = body;

    // Validate input
    if (!name || !email || !password) {
      return NextResponse.json(
        { success: false, message: 'All fields are required' },
        { status: 400 }
      );
    }

    if (password !== password_confirmation) {
      return NextResponse.json(
        { success: false, message: 'Passwords do not match' },
        { status: 400 }
      );
    }

    // Call backend API
    const payload = { 
      name, 
      email, 
      password, 
      password_confirmation,
      marketing_consent,
      roleSelected,
      captchaToken
    };
    
    const response = await fetch(`${API_BASE_URL}/register`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    });

    const data = await response.json();

    if (!response.ok || !data.success) {
      // Handle specific error cases
      let errorMessage = data.message || 'Registration failed';
      
      if (response.status === 429) {
        errorMessage = 'Too many registration attempts. Please try again in a minute.';
      } else if (response.status === 422 || response.status === 400) {
        errorMessage = data.message || 'Please check your input and try again.';
      }
      
      return NextResponse.json(
        { success: false, message: errorMessage, errors: data.errors || data.data },
        { status: response.status }
      );
    }

    // Set secure HTTP-only cookies
    const cookieStore = await cookies();
    
    cookieStore.set('token', data.access_token, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      maxAge: 60 * 60 * 24 * 7,
      path: '/',
    });

    cookieStore.set('getUser', JSON.stringify(data.data), {
      httpOnly: false,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      maxAge: 60 * 60 * 24 * 7,
      path: '/',
    });

    // Return minimal data - sensitive info is in cookies
    return NextResponse.json({
      success: true,
      message: 'Registration successful',
      data: {
        name: data.data?.name,
        email: data.data?.email,
        otp: data.data?.otp, // Needed for verification flow
      },
    });
  } catch (error: any) {
    console.error(
      error instanceof Error ? error.message : 'Registration request failed'
    );
    return NextResponse.json(
      { success: false, message: error.message || 'Internal server error' },
      { status: 500 }
    );
  }
}
