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

const LARAVEL_SOCIAL_LOGIN =
  "https://api.astrology.togwe.com/api/user/social/web-login";

export async function POST(request: NextRequest) {
  console.log("====================================");
  console.log("SOCIAL LOGIN NEXT.JS ROUTE CALLED");
  console.log("====================================");

  try {
    const body = await request.json();

    console.log("Received body:");
    console.log({
      has_id_token: !!body.id_token,
      device_token: body.device_token,
      device_name: body.device_name,
    });

    if (!body.id_token) {
      return NextResponse.json(
        {
          success: false,
          message: "id_token is required",
        },
        { status: 400 }
      );
    }

    const laravelResponse = await fetch(
      LARAVEL_SOCIAL_LOGIN,
      {
        method: "POST",

        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
        },

        body: JSON.stringify({
          id_token: body.id_token,
          device_token:
            body.device_token || "browser-device",
          device_name:
            body.device_name || "browser",
        }),

        cache: "no-store",
      }
    );

    console.log(
      "Laravel status:",
      laravelResponse.status
    );

    const responseText =
      await laravelResponse.text();

    console.log(
      "Laravel response:",
      responseText.substring(0, 1000)
    );

    let data: any;

    try {
      data = JSON.parse(responseText);
    } catch (error) {
      console.error(
        "Laravel returned non-JSON response"
      );

      return NextResponse.json(
        {
          success: false,
          message:
            "Laravel API returned non-JSON response",
          status: laravelResponse.status,
          response:
            responseText.substring(0, 1000),
        },
        {
          status: 502,
        }
      );
    }

    return NextResponse.json(data, {
      status: laravelResponse.status,
    });
  } catch (error) {
    console.error(
      "SOCIAL LOGIN ROUTE ERROR:",
      error
    );

    return NextResponse.json(
      {
        success: false,
        message:
          "Unable to connect to social login server",
      },
      {
        status: 500,
      }
    );
  }
}