import axios from "axios";
import { getStoredLocale } from "@/lib/getLocale";

export interface TwoFactorAuthMethods {
  whatsapp?: boolean;
  email?: boolean;
  phone_number?: boolean;
}

export const getAccountSettings = async (token?: string): Promise<any> => {
  try {
    const locale = getStoredLocale();
    const url = `${process.env.NEXT_PUBLIC_API_URL}/profile/account-settings`;
    const headers: Record<string, string> = {
      "Content-Type": "application/json",
      Authorization: token ? `Bearer ${token}` : "",
      "Accept-Language": locale,
      Accept: "application/json",
    };
    const response = await axios.get(url, { headers, withCredentials: true });
    const result = response?.data?.data;
    return {
      success: true,
      message: "Fetch data success",
      data: result,
    };
  } catch (error: any) {
    throw error;
  }
};

export const updateAccountSettings = async (
  payload: {
    notification_settings?: {
      recommendations?: boolean;
      receive_updates_on_whatsapp?: boolean;
      receive_updates_and_offers?: boolean;
    };
    two_factor_authentication?: {
      whatsapp?: boolean;
      email?: boolean;
      phone_number?: boolean;
    };
    otp?: string;
  },
  token?: string
): Promise<any> => {
  try {
    const locale = getStoredLocale();
    const url = `${process.env.NEXT_PUBLIC_API_URL}/profile/account-settings`;
    const headers: Record<string, string> = {
      "Content-Type": "application/json",
      Authorization: token ? `Bearer ${token}` : "",
      "Accept-Language": locale,
      Accept: "application/json",
    };

    const response = await axios.put(url, payload, {
      headers,
      withCredentials: true,
    });

    const result = response?.data;

    if (
      response.status === 403 &&
      result?.error_type === "TWO_FACTOR_REQUIRED"
    ) {
      return {
        success: false,
        requiresOTP: true,
        userId: result.user_id,
        message: "OTP verification required",
        error: result.message,
      };
    }

    return {
      success: true,
      message: result?.message || "Update successful",
      data: result?.data,
    };
  } catch (error: any) {
    if (
      error.response?.status === 400 &&
      error.response?.data?.error_type === "OTP_INVALID_OR_EXPIRED"
    ) {
      return {
        success: false,
        message: error.response.data.message || "Invalid or expired OTP",
        error: "OTP_INVALID_OR_EXPIRED",
      };
    }
    throw error;
  }
};

export const connectSocialAccount = async (
  provider: "google" | "facebook" | "apple",
  providerId: string,
  token?: string
): Promise<any> => {
  try {
    const locale = getStoredLocale();
    const url = `${process.env.NEXT_PUBLIC_API_URL}/profile/social-account/connect`;
    const headers: Record<string, string> = {
      "Content-Type": "application/json",
      Authorization: token ? `Bearer ${token}` : "",
      "Accept-Language": locale,
      Accept: "application/json",
    };
    // Only use the providerId passed in, do not generate or prompt for it
    const response = await axios.post(
      url,
      { provider, providerId },
      { headers, withCredentials: true }
    );
    return response.data;
  } catch (error) {
    throw error;
  }
};

export const resend2FAVerificationOtp = async (
  twoFactorAuth: TwoFactorAuthMethods,
  token?: string
): Promise<{
  success: boolean;
  message: string;
  via?: string[];
  error?: string;
}> => {
  try {
    const locale = getStoredLocale();
    const url = `${process.env.NEXT_PUBLIC_API_URL}/profile/account-settings/resend-otp`;
    const headers: Record<string, string> = {
      "Content-Type": "application/json",
      Authorization: token ? `Bearer ${token}` : "",
      "Accept-Language": locale,
      Accept: "application/json",
    };

    const response = await axios.put(
      url,
      { two_factor_authentication: twoFactorAuth },
      { headers, withCredentials: true }
    );

    const result = response?.data;

    if (response.status === 200) {
      return {
        success: true,
        message: result.message || "OTP resent successfully",
        via: result.data?.via,
      };
    }

    return {
      success: false,
      message: result?.message || "Failed to resend OTP",
      error: result?.error_type,
    };
  } catch (error: any) {
    if (error.response?.data) {
      return {
        success: false,
        message: error.response.data.message || "Failed to resend OTP",
        error: error.response.data.error_type || "RESEND_OTP_FAILED",
      };
    }

    throw error;
  }
};
