"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;
  const returnUrl = (formData.get("returnUrl") as string) || "/";

  const handle = rawHandle?.trim().replace(/^@/, "");

  if (!handle) {
    redirect("/login?error=" + encodeURIComponent("Please enter your handle"));
  }

  let authorizationUrl: string;

  try {
    const client = await getOAuthClient();

    const url = await client.authorize(handle, {
      scope: "atproto transition:generic",
      state: JSON.stringify({ returnUrl }),
    });

    authorizationUrl = url.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);
}
