import apiFetch from '@wordpress/api-fetch';

export const fetchAcfForPost = async ({ restBase, id, field }) => {
  try {
    const res = await apiFetch({ path: `/acf/v3/${restBase}/${id}` });
    if (res?.acf && Object.prototype.hasOwnProperty.call(res.acf, field)) return res.acf[field];
  } catch {}
  try {
    const wp = await apiFetch({ path: `/wp/v2/${restBase}/${id}` });
    if (wp?.acf && Object.prototype.hasOwnProperty.call(wp.acf, field)) return wp.acf[field];
  } catch {}
  return undefined;
};

export const fetchAcfForTerm = async ({ taxonomy, restBase, id, field }) => {
  try {
    const res = await apiFetch({ path: `/acf/v3/terms/${taxonomy}/${id}` });
    if (res?.acf && Object.prototype.hasOwnProperty.call(res.acf, field)) return res.acf[field];
  } catch {}
  try {
    const wp = await apiFetch({ path: `/wp/v2/${restBase}/${id}` });
    if (wp?.acf && Object.prototype.hasOwnProperty.call(wp.acf, field)) return wp.acf[field];
  } catch {}
  return undefined;
};
