interface SendOtpPayload {
  mobileNumber?: string;
  type: string;
  amount?: number;
  beneficiary?: string;
  ifsc?: string;
  acctFrom?: string;
  acctTo?: string;
  ref?: string;
  date?: string;
  userOtp?: string;
  username?: string;
  PreferName?: string;
}

function getStoredMobileNumber(): string {
  const mobileNumber = localStorage.getItem('remitter_mobile_no');
  // const mobileNumber = "7890544527";
  if (!mobileNumber) throw new Error('Mobile number not found.');
  return mobileNumber;
}

export async function sendOtp(payload: SendOtpPayload) {
  const mobileNumber = payload.mobileNumber || getStoredMobileNumber();

  const response = await fetch('/api/otp/send', {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-Login-Type": "IB",
    },
    body: JSON.stringify({ ...payload, mobileNumber }),
  });

  const data = await response.json();

  if (!response.ok) {
    console.log('OTP sended failed.');
    const errorMsg = data?.error || 'Send OTP failed. Please try again later.';
    throw new Error(errorMsg);
  }
  console.log('OTP sended.');
  return data;
}

export async function verifyOtp(otp: string) {
  const mobileNumber = getStoredMobileNumber();

  const response = await fetch(`/api/otp/verify?mobileNumber=${mobileNumber}`, {
    method: "POST",
    headers: { "Content-Type": "application/json", "X-Login-Type": "IB" },
    body: JSON.stringify({ otp }),
  });

  const data = await response.json();

  if (!response.ok) {
    console.log('OTP not verified.');
    const errorMsg = data?.error || 'OTP verification failed.';
    throw new Error(errorMsg);
  }
  console.log('OTP verified.');
  return data;
}

export async function verifyLoginOtp(otp: string, mobileNumber: string) {
  const response = await fetch(`/api/otp/verify?mobileNumber=${mobileNumber}`, {
    method: "POST",
    headers: { "Content-Type": "application/json", "X-Login-Type": "IB", },
    body: JSON.stringify({ otp }),
  });

  const data = await response.json();

  if (!response.ok) {
    console.log('Login OTP not verified.');
    const errorMsg = data?.error || 'OTP verification failed.';
    throw new Error(errorMsg);
  }
  console.log("Login OTP verified");
  return data;
}
