import axios from "axios";
import Cookies from "js-cookie";

const tokenUrl = `${process.env.NEXT_PUBLIC_API_URL}/api-token-auth/`;
const checkUrl = `${process.env.NEXT_PUBLIC_API_URL}/api-token-verify/`;

export async function generateToken(username: string, password: string): Promise<string> {
  const resp = await axios.post(tokenUrl, {
    username,
    password,
  });
  return resp.data.token;
}

export function setTokenCookie(token: string) {
  Cookies.set("jwt", token);
  Cookies.set("jwt", token, { domain: ".sahkoinsinoorikilta.fi" });
}

export function getTokenCookie(): string {
  return Cookies.get("jwt");
}

export function deleteTokenCookie(): void {
  Cookies.remove("jwt", { domain: ".sahkoinsinoorikilta.fi" });
  Cookies.remove("jwt");
}

export async function isAuthenticated(): Promise<boolean> {
  try {
    const token = getTokenCookie();
    await axios.post(checkUrl, {
      token,
    });
    return true;
  } catch (err) {
    // remove the cookie since it's invalid
    deleteTokenCookie();
    return false;
  }
}

export function getAuthHeader(): string {
  const jwt = getTokenCookie();
  return `JWT ${jwt}`;
}
