import { apiFetch, ApiError } from "@/lib/api/server";
import type { AuthUser } from "@/types/user";

export async function getCurrentUser(): Promise<AuthUser | null> {
  try {
    // "optional" — this runs on public pages too (e.g. the navbar) to probe
    // "is anyone logged in"; a 401 here must return null, never redirect.
    const res = await apiFetch<{ data: AuthUser }>("/auth/me", { auth: "optional" });
    return res.data;
  } catch (error) {
    if (error instanceof ApiError && error.status === 401) {
      return null;
    }
    throw error;
  }
}

/** GET /auth/verify-email — FR-103, public (the signed query params are the credential). */
export async function verifyEmail(params: { id: string; expires: string; signature: string }) {
  const qs = new URLSearchParams(params).toString();
  try {
    const res = await apiFetch<{ message: string }>(`/auth/verify-email?${qs}`);
    return { success: true, message: res.message };
  } catch (error) {
    if (error instanceof ApiError) {
      return { success: false, message: error.message };
    }
    throw error;
  }
}
