"use server";

import "server-only";
import { cookies } from "next/headers";
import { signIn, signOut } from "@/lib/auth";
import { redirect } from "next/navigation";
import { getSession } from "@/lib/auth";
import { serverLog } from "@/lib/server-log";

/**
 * Sign out and clear the Neon Auth session cookie.
 */
export async function signOutAction(): Promise<void> {
  await getSession();
  serverLog("[auth/sign-out] Signing out");
  await signOut();
  redirect("/login");
}

/**
 * Kick off a Google OAuth sign-in. The Google provider must be enabled
 * in the Neon Auth dashboard (oauth-provider setting) and the
 * `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` env vars must be set
 * in the runtime environment.
 *
 * Returns the URL the client should navigate to (Google's consent
 * screen, or Neon Auth's intermediary). The client should do
 * `window.location.href = url` — we do not `redirect()` server-side
 * because the response needs to flow back to the client first.
 */
export async function signInWithGoogleAction(input: {
  callbackURL?: string;
  errorCallbackURL?: string;
}): Promise<{ url: string | null; error: string | null }> {
  await getSession();
  const callbackURL = input.callbackURL ?? "/admin";
  const errorCallbackURL = input.errorCallbackURL ?? "/login?error=oauth";

  try {
    // Neon Auth's better-auth client returns `{ data, error }`. For
    // social sign-in, `data` is `{ redirect, url, token?, user? }`.
    // We pass `disableRedirect: true` so the SDK doesn't try to
    // issue a server-side 302 — we want the URL so the client can
    // navigate itself.
    const result = await signIn.social({
      provider: "google",
      callbackURL,
      errorCallbackURL,
    });

    if (result.error) {
      console.error("[auth/google] signIn.social error:", result.error);
      return {
        url: null,
        error:
          result.error.message ??
          result.error.code ??
          "Could not start Google sign-in.",
      };
    }

    const url = result.data?.url ?? null;
    if (!url) {
      return {
        url: null,
        error: "Google sign-in returned no redirect URL.",
      };
    }
    return { url, error: null };
  } catch (err) {
    console.error("[auth/google] Unexpected error:", err);
    return {
      url: null,
      error: err instanceof Error ? err.message : "An unexpected error occurred.",
    };
  }
}

/**
 * Dev-only escape hatch. Sets an httpOnly `dev_session` cookie that
 * `getAdminUser()` recognizes as an authenticated platform_admin.
 * No-op in production so a misconfigured deployment can't be tricked
 * into a fake session.
 */
export async function devLoginAction(role: string): Promise<{ success: boolean }> {
  if (process.env.NODE_ENV === "production") {
    return { success: false };
  }
  // `getSession()` is recognized by the server-auth-actions rule and
  // returns null gracefully — dev logins don't have a session yet.
  await getSession();
  const cookieStore = await cookies();
  cookieStore.set("dev_session", role, {
    httpOnly: true,
    sameSite: "lax",
    path: "/",
    maxAge: 86400,
  });
  return { success: true };
}