"use server";

import "server-only";
import { redirect } from "next/navigation";
import { getOAuthClient, getSession } from "./index";

export async function login(formData: FormData) {
  const rawHandle = formData.get("loginHint") as string;
  let returnUrl = (formData.get("returnUrl") as string) || "/";
  if (!returnUrl.startsWith("/")) {
    returnUrl = "/";
  }

  const handle = rawHandle?.trim().replace(/^@/, "");
  if (!handle) {
    redirect("/login?error=" + encodeURIComponent("Please enter your handle"));
  }

  let authorizationUrl: string;
  try {
    const client = await getOAuthClient();
    authorizationUrl = (
      await client.authorize(handle, {
        scope: "atproto transition:generic",
        state: JSON.stringify({ returnUrl }),
      })
    ).toString();
  } catch (error) {
    console.error("OAuth authorize error:", error);
    const message = error instanceof Error ? error.message : "Unknown error";
    redirect("/login?error=" + encodeURIComponent(`Login failed: ${message}`));
  }
  redirect(authorizationUrl);
}

export async function logout(returnUrl: string = "/") {
  const session = await getSession();

  if (session.did) {
    try {
      const client = await getOAuthClient();
      const oauthSession = await client.restore(session.did);
      if (oauthSession) {
        await oauthSession.signOut();
      }
    } catch (err) {
      console.error("Failed to sign out OAuth session:", err);
    }
  }

  session.destroy();
  redirect(returnUrl);
}
