import apiClient from "../api-client";
import {
  ConfirmUser,
  ForgotPassword,
  ResetPassword,
  ChangePassword,
  SignInModel,
  SignInResponse,
  SignUpModel,
  SocialSignInModel,
} from "../types/models";

export default class authService {
  static signUp = async (payload: SignUpModel) => {
    try {
      const response = await apiClient.post(`/api/auth/register`, payload);
      return response.data;
    } catch (error) {
      console.error(`Error in authService:signup`, error);
      throw error;
    }
  };

  static signIn = async (payload: SignInModel) => {
    try {
      const response = await apiClient.post(`/api/auth/login`, payload);
      return response.data as SignInResponse;
    } catch (error) {
      console.error(`Error in authService:signin`, error);
      throw error;
    }
  };

  static forgotPassword = async (payload: ForgotPassword) => {
    try {
      const response = await apiClient.post(`/api/auth/forgot-password`, payload);
      return response.data;
    } catch (error) {
      console.error(`Error in authService:forgotpassword`, error);
      throw error;
    }
  };

  static resetPassword = async (payload: ResetPassword) => {
    try {
      const response = await apiClient.post(`/api/auth/reset-password`, payload);
      return response.data;
    } catch (error) {
      console.error(`Error in authService:reset`, error);
      throw error;
    }
  };

  static changePassword = async (payload: ChangePassword) => {
    try {
      const response = await apiClient.post(`/api/auth/change-password`, payload);
      return response.data;
    } catch (error) {
      console.error(`Error in authService:reset`, error);
      throw error;
    }
  };

  static confirmLink = async (token: string) => {
    try {
      const response = await apiClient.get(`/api/auth/verify-email?token=${token}`);
      return response.data;
    } catch (error) {
      console.error(`Error in authService:reset`, error);
      throw error;
    }
  };

  static resendConfirmLink = async (email: string) => {
    try {
      const response = await apiClient.post(`/api/auth/send-verification`, { email });
      return response.data;
    } catch (error) {
      console.error(`Error in authService:resendConfirm`, error);
      throw error;
    }
  };

  static googleUserinfo = async (token: string) => {
    try {
      const response = await apiClient.get(
        `https://www.googleapis.com/oauth2/v3/userinfo`,
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        }
      );
      return response.data;
    } catch (error) {
      console.error(`Error in authService:socialSignIn`, error);
      throw error;
    }
  };

  static socialSignIn = async (payload: SocialSignInModel) => {
    try {
      const response = await apiClient.post(
        `/socialsignin`,
        { token: payload.token, provider: payload.provider },
        {
          headers: {
            token: payload.token,
            email: payload.email,
            firstname: payload.firstName,
            lastname: payload.lastName,
          },
        }
      );
      return response.data as SignInResponse;
    } catch (error) {
      console.error(`Error in authService:socialSignIn`, error);
      throw error;
    }
  };

  static refreshToken = async (token: string) => {
    try {
      const response = await apiClient.post(`/v1/api/auth`, { token: token });
      return response.data;
    } catch (error) {
      console.error(`Error in authService:refreshToken`, error);
      throw error;
    }
  };

  static getSendDesignData = async (token: string) => {
    try {
      const response = await apiClient.get(`/api/customer-send-design/thread/${token}`);
      const resp = response.data;
      if (resp.success && resp.data) {
        const order = resp.data;
        const lastLog =
          Array.isArray(order.logs) && order.logs.length > 0
            ? order.logs[order.logs.length - 1]
            : null;
        const sendImagePath = lastLog?.imagesArray?.[0];
        const replaceImage = JSON.parse(
          JSON.stringify(lastLog?.imagesArray || [])
        );
        let attributes = [];
        if (Array.isArray(order.product?.options) && order.product.options.length) {
          attributes = order.product.options.map(
            (option: any) => ({
              displayName:
                option.variantItemId?.attributeItemId?.displayName ||
                option.variantItemId?.attributeItemId?.name ||
                "",
              attributeType:
                option.variantItemId?.variantId?.attributeType?.name ||
                option.variantItemId?.attributeType?.name ||
                "",
            })
          );
        }

        return {
          success: true,
          data: { ...order, lastLog, sendImagePath, replaceImage, attributes },
        };
      } else {
        console.log(resp)

        return { success: false, message: resp.message };
      }
    } catch (error) {
      console.error(`Error in authService:getSendDesignData`, error);
      return { success: false, message: "API call failed" };
    }
  };

  static updateThread = async (payload: any) => {
    try {
      const response = await apiClient.post(`/api/customer-send-design/thread`, payload);
      return response.data;
    } catch (error) {
      console.error(`Error in authService:updateThread`, error);
      return { success: false, message: "API call failed" };
    }
  };
}
