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

const API_BASE_URL = process.env.API_BASE_URL;

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { email, otp } = body;

    if (!email || !otp) {
      return NextResponse.json(
        { success: false, message: "Email and OTP are required" },
        { status: 400 }
      );
    }

    const cookieStore = await cookies();
    const token = cookieStore.get("token")?.value;

    const response = await fetch(`${API_BASE_URL}/otp-confirm`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        ...(token && { Authorization: `Bearer ${token}` }),
      },
      body: JSON.stringify({ email, otp }),
    });

    const data = await response.json();

    // If OTP verification successful, set cookies like login does
    if (response.ok && data.success) {
      const cookieStore = await cookies();
      
      // Check if backend returns access_token directly or needs to be fetched from data.data
      const accessToken = data.access_token || data.data?.access_token || data.token;
      const userData = data.data || data.user;
      
      if (accessToken) {
        // Server-side HTTP-only token (secure)
        cookieStore.set('token', accessToken, {
          httpOnly: true,
          secure: process.env.NODE_ENV === 'production',
          sameSite: 'lax',
          maxAge: 60 * 60 * 24 * 7, // 7 days
          path: '/',
        });

        // Also set client-side token for backward compatibility
        cookieStore.set('token_client', accessToken, {
          httpOnly: false, // Accessible by client
          secure: process.env.NODE_ENV === 'production',
          sameSite: 'lax',
          maxAge: 60 * 60 * 24 * 7, // 7 days
          path: '/',
        });
      }

      if (userData) {
        cookieStore.set('getUser', JSON.stringify(userData), {
          httpOnly: false, // Accessible by client for UI
          secure: process.env.NODE_ENV === 'production',
          sameSite: 'lax',
          maxAge: 60 * 60 * 24 * 7,
          path: '/',
        });
      }

      // Return response with client-accessible token for legacy support
      return NextResponse.json({
        success: true,
        message: data.message || 'OTP verification successful',
        access_token: accessToken, // For client-side cookie setting
        has_user_allow_to_share_vision_board: userData?.has_user_allow_to_share_vision_board,
        data: userData,
        // Flag to indicate if we need client to redirect to login
        needs_login: !accessToken,
      });
    }

    return NextResponse.json(data, { status: response.status });
  } catch (error: any) {
    console.error(
      error instanceof Error ? error.message : 'OTP verification request failed'
    );
    return NextResponse.json(
      { success: false, message: "Something went wrong. Please try again." },
      { status: 500 }
    );
  }
}
