import { API_ENDPOINTS, buildApiUrl } from '@/assets/config/api';
import { ApiMessageResponse } from '@/assets/types';
import CryptoJS from 'crypto-js';

async function postToEndpoint(
  endpoint: string,
  fields: Record<string, string>,
): Promise<ApiMessageResponse> {
  const formData = new FormData();
  Object.entries(fields).forEach(([key, value]) => formData.append(key, value));

  const response = await fetch(buildApiUrl(endpoint), {
    method: 'POST',
    headers: { Accept: 'application/json' },
    body: formData,
  });

  return response.json();
}

export async function recoverPassword(email: string): Promise<ApiMessageResponse> {
  return postToEndpoint(API_ENDPOINTS.RECOVER_PASSWORD, { email: email.trim() });
}

export async function confirmRecoveryToken(
  email: string,
  token: string,
): Promise<ApiMessageResponse> {
  return postToEndpoint(API_ENDPOINTS.CONFIRM_TOKEN, {
    email: email.trim(),
    token: token.trim(),
  });
}

export async function resetPassword(
  email: string,
  token: string,
  password: string,
  confirmPassword: string,
): Promise<ApiMessageResponse> {
  const encryptedPassword = CryptoJS.MD5(password).toString();
  const encryptedConfirm = CryptoJS.MD5(confirmPassword).toString();

  return postToEndpoint(API_ENDPOINTS.RESET_PASSWORD, {
    email: email.trim(),
    token: token.trim(),
    password: encryptedPassword,
    confirmPassword: encryptedConfirm,
  });
}
