import api from "src/api";

export const getAddresses = async (origin, originId) => {
  const { data } = await api.get(`/addresses?source=${origin}&source_id=${originId}`);
  return data.payload;
};

export const getAddress = async (id) => {
  const { data } = await api.get(`/addresses/${id}`);
  return data.payload;
};

export const createAddress = async (address) => {
  const { data } = await api.post(`/addresses`, { ...address });
  return data.payload;
};

export const updateAddress = async (address, id) => {
  const { data } = await api.put(`/addresses/${id}`, { ...address });
  return data.payload;
};

export const deleteAddress = async (id) => {
  const { data } = await api.delete(`/addresses/${id}`);
  return data.payload;
};

export const searchAddressByCEP = async (cep) => {
  try {
    const responseCep = await fetch(`https://viacep.com.br/ws/${cep}/json/`);
    const data = await responseCep.json();

    if (data.erro) {
      return null;
    }

    const response = await api.get('busca-estado-cidade-por-descricao', {
      params: {
        stateUf: data.uf,
        cityName: data.localidade
      }
    });
    
    return {
      zip_code: data.cep,
      address: data.logradouro,
      district: data.bairro,
      city_id: response.data.payload.city.value,
      state_id: response.data.payload.state.value,
      city: {
        id: response.data.payload.city.value,
        name: response.data.payload.city.label
      },
      state: {
        id: response.data.payload.state.value,
        name: response.data.payload.state.label
      }
    };
  } catch {
    return null;
  }
};

export function getClientAddresses (clientId, source) {
  return api.get(`/addresses?source=${source}&source_id=${clientId}`)
}

export function getPrimaryAddress (clientId, source) {
  return api.get(`/addresses-primary?source=${source}&source_id=${clientId}`)
}
