"use server";
import { fetchData, fetchDataWithToken } from "../api-fetcher";
import { baseUrl } from "../basics";

const createPasswordEndpoint = `${baseUrl}/authentication/create_password`;
const changePasswordEndpoint = `${baseUrl}/authentication/change_password`;
const forgotPasswordEndpoint = `${baseUrl}/authentication/reset_password`;

interface createPasswordViaToken {
  token: string;
  password: string;
  rePassword: string;
}

interface changePasswordViaToken {
  oldPassword: string;
  newPassword: string;
}

interface sendForgotPasswordEmail {
  domain: string;
  accessKey: string;
}

async function create_password_via_token(payload: createPasswordViaToken) {
  const createPasswordResponse: any = await fetchData(
    createPasswordEndpoint,
    {
      password_token: payload.token,
      password: payload.password,
      re_password: payload.rePassword,
    },
    "POST",
    false
  );
  return createPasswordResponse;
}

async function change_password_via_token(payload: changePasswordViaToken) {
  const changePasswordResponse: any = await fetchDataWithToken(
    changePasswordEndpoint,
    {
      old_password: payload.oldPassword,
      new_password: payload.newPassword,
    },
    "POST",
    false
  );
  return changePasswordResponse;
}

async function send_forgot_password_email(payload: sendForgotPasswordEmail) {
  const response: any = await fetchData(
    forgotPasswordEndpoint,
    {
      domain: payload.domain,
      access_key: payload.accessKey,
    },
    "POST",
    false
  );
  return response;
}

export {
  create_password_via_token,
  change_password_via_token,
  send_forgot_password_email,
};
