import type { APIRoute } from "astro";

const PB_POCKETBASE_URL = import.meta.env.PB_POCKETBASE_URL || "http://localhost:8090";

export const GET: APIRoute = async ({ cookies, request }) => {
  try {
    const pbAuthCookie = cookies.get("pb_auth")?.value;

    if (!pbAuthCookie) {
      return new Response(
        JSON.stringify({ authenticated: false, user: null }),
        { status: 200, headers: { "Content-Type": "application/json" } }
      );
    }

    const token = pbAuthCookie.trim();

    const response = await fetch(
      `${PB_POCKETBASE_URL}/api/collections/users/auth-refresh`,
      {
        method: "POST",
        headers: {
          Authorization: `Bearer ${token}`,
          "Content-Type": "application/json",
        },
      }
    );

    if (!response.ok) {
      if (cookies.has("pb_auth")) {
        cookies.delete("pb_auth", { path: "/" });
      }
      return new Response(
        JSON.stringify({ authenticated: false, user: null }),
        { status: 200, headers: { "Content-Type": "application/json" } }
      );
    }

    const data = await response.json();

    const isHttps = request.headers.get("x-forwarded-proto") === "https";

    cookies.set("pb_auth", data.token, {
      path: "/",
      maxAge: 60 * 60 * 24 * 7,
      httpOnly: false,
      secure: isHttps,
      sameSite: "lax",
    });

    const fullName = [data.record.firstName, data.record.lastName].filter(Boolean).join(" ") || data.record.email;

    return new Response(
      JSON.stringify({
        authenticated: true,
        user: {
          id: data.record.id,
          email: data.record.email,
          name: fullName,
          avatar: data.record.avatar,
          verified: data.record.verified,
        },
      }),
      { status: 200, headers: { "Content-Type": "application/json" } }
    );
  } catch (error) {
    console.error("[AUTH ME] Error:", error);
    return new Response(
      JSON.stringify({ authenticated: false, error: "Ошибка сервера" }),
      { status: 500, headers: { "Content-Type": "application/json" } }
    );
  }
};