import axios from "axios";
import {
  AuthenticationRequest,
  IUser,
  RequestLoginActivity,
} from "../types/user";
import axiosInstance, { axiosInstancee, endpoints } from "@/utils/axios";
import useSWR from "swr";
import { useMemo } from "react";
import { GATEWAY} from "@/config-global";
import { IAgency } from "../types/agency";

export const loginUser = async (authData: AuthenticationRequest) => {
  try {
    const response = await axiosInstancee.post(
      "/api/user/auth/signin",
      authData
    );
    return response;
  } catch (error) {
    throw error;
  }
};
export function useGetUserByEmail(email: string) {
  const fetcher = (url: string) => fetch(url).then((res) => res.json());
  const URL = [endpoints.user.getByEmail(email)];
  const { data, error } = useSWR<IUser>(URL, fetcher);
  const memoizedValue = useMemo(
    () => ({
      userData: (data as IUser) || null,
      userError: error,
    }),
    [data, error]
  );
  return memoizedValue;
}
export const ChangingLogingActivity = async (
  requestLoginActivity: RequestLoginActivity
) => {
  try {
    const response = await axios.post(
      endpoints.user.changingLogingActivity,
      requestLoginActivity
    );
    return response;
  } catch (error) {
    throw error;
  }
};
// Get user by email
const apiUrl = endpoints.user.user;
export const getUserByEmail = async (email: string): Promise<IUser> => {
  const token = localStorage.getItem("token");
  if (!token) {
    throw new Error("No authentication token found");
  }

  try {
    const response = await axiosInstance.get(`${apiUrl}/email/${email}`, {
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json",
      },
    });
    return response.data;
  } catch (error) {
    console.error("Error fetching user by email:", error);
    throw error;
  }
};

export const getUserById = async (userId: number): Promise<IUser> => {
  try {
    const token = localStorage.getItem("token");
    if (!token) {
      throw new Error("No authentication token found");
    }

    const response = await axiosInstance.get(`${apiUrl}/${userId}`, {
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json",
      },
    });
    return response.data;
  } catch (error) {
    console.error("Error fetching user by ID:", error);
    throw error;
  }
};

export async function getUserCurrency(): Promise<string> {
  const email = localStorage.getItem("email");
  const token = localStorage.getItem("token");

  if (!email) {
    throw new Error("User email not found in localStorage");
  }

  if (!token) {
    throw new Error("User token not found in localStorage");
  }

  try {
    const response = await axiosInstance.get(
      `/api/user/currency?email=${email}`,
      {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      }
    );
    return response.data;
  } catch (error) {
    console.error("Error fetching user currency:", error);
    return "USD";
  }
}
export const getAgencyById = async (agencyId: string | number): Promise<IAgency> => {
  try {
    const token = localStorage.getItem("token");
    if (!token) {
      throw new Error("No authentication token found");
    }

    const response = await axiosInstance.get(endpoints.user.getById(agencyId), {
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json",
      },
    });
    return response.data;
  } catch (error) {
    console.error("Error fetching agency by ID:", error);
    throw error;
  }
};

