// The Lucia project.
// Copyright 2023-2026 DSP, inc.  All rights reserved.
// Authors:
//   imacat.yang@dsp.im (imacat), 2023/9/23
/** @module auth Authentication token refresh utilities. */

import axios from "axios";
import {
  getCookie,
  setCookie,
  setCookieWithoutExpiration,
} from "@/utils/cookieUtil.js";

/**
 * Refreshes the access token using the stored refresh token cookie.
 *
 * Uses plain axios (not apiClient) to avoid interceptor loops. Updates
 * both the access token (session cookie) and refresh token (6-month
 * expiry) cookies.
 *
 * @returns {Promise<string>} The new access token.
 * @throws {Error} If the refresh request fails.
 */
export async function refreshTokenAndGetNew() {
  const api = "/api/oauth/token";
  const config = {
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
  };
  const data = {
    grant_type: "refresh_token",
    refresh_token: getCookie("luciaRefreshToken"),
  };

  const response = await axios.post(api, data, config);
  const newAccessToken = response.data?.access_token;
  const newRefreshToken = response.data?.refresh_token;
  if (!newAccessToken || !newRefreshToken) {
    throw new Error("Invalid token response structure");
  }

  setCookieWithoutExpiration("luciaToken", newAccessToken);
  // Expire in ~6 months
  const expiredMs = new Date();
  expiredMs.setMonth(expiredMs.getMonth() + 6);
  const days = Math.ceil(
    (expiredMs.getTime() - Date.now()) / (24 * 60 * 60 * 1000),
  );
  setCookie("luciaRefreshToken", newRefreshToken, days);

  return newAccessToken;
}
