import client from "./client";
import type { User } from "../types/models";

/**
 * Authenticate the user.
 *
 * The backend sets an HttpOnly cookie with the JWT — no token is stored
 * in JavaScript memory or localStorage.
 */
export async function login(
  username: string,
  password: string,
): Promise<void> {
  const params = new URLSearchParams();
  params.append("username", username);
  params.append("password", password);

  await client.post("/auth/login", params, {
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
  });
}

/** Clear the authentication cookie on the server. */
export async function logout(): Promise<void> {
  try {
    await client.post("/auth/logout");
  } catch {
    // Best-effort — the cookie will expire anyway
  }
}

/** Fetch the currently authenticated user profile. */
export async function getMe(): Promise<User> {
  const { data } = await client.get<User>("/auth/me");
  return data;
}

/** Silently renew the session cookie. Throws if there is nothing to renew. */
export async function refreshToken(): Promise<void> {
  await client.post("/auth/refresh");
}

/** Change the current user's password. */
export async function changePassword(
  currentPassword: string,
  newPassword: string,
): Promise<void> {
  await client.post("/auth/change-password", {
    current_password: currentPassword,
    new_password: newPassword,
  });
}
