import { addToFavorites, getBySkuid } from "@/api/system/favoriteProduct";

function parseMaybeJson(str) {
  if (!str || typeof str !== 'string') return null;
  try { return JSON.parse(str); } catch(e) { return null; }
}

function getNested(obj, path) {
  try {
    if (!obj) return null;
    const segs = path.split('.');
    let cur = obj;
    for (const k of segs) {
      if (cur && typeof cur === 'object' && k in cur) cur = cur[k]; else return null;
    }
    return cur;
  } catch(e) { return null; }
}

export function parsePublishResponse(res) {
  try {
    const d = res && res.data ? res.data : res;
    const productId = d?.product_id ?? d?.productId ?? d?.data?.product_id ?? d?.data?.productId ?? null;
    const productStatus = d?.product_status ?? d?.productStatus ?? d?.data?.product_status ?? d?.data?.productStatus ?? null;
    const outerId = d?.outer_id ?? d?.outerId ?? d?.data?.outer_id ?? d?.data?.outerId ?? null;
    return { productId, productStatus, outerId };
  } catch(e) { return { productId: null, productStatus: null, outerId: null }; }
}

function buildFavoriteFromTransfer(product, pub) {
  const spuid = product?.spuid || product?.skuId || product?.skuid || '';
  return {
    skuid: spuid,
    productName: product?.skuName || product?.title || '',
    shopName: product?.shopName || '',
    productUrl: product?.url || '',
    productImage: Array.isArray(product?.images) && product.images.length ? product.images[0] : '',
    price: (product?.price != null ? String(product.price) : (product?.lowestCouponPrice != null ? String(product.lowestCouponPrice) : '')),
    commissionInfo: product?.commissionShare ? `${product.commissionShare}%` : (product?.commission != null ? String(product.commission) : ''),
    remark: `自动添加 - 发品时间: ${new Date().toLocaleString()}${pub.outerId ? `, 商家编码: ${pub.outerId}` : ''}`,
    productId: pub.productId,
    productStatus: pub.productStatus
  };
}

function buildFavoriteFromXb(child, pub) {
  const jq = parseMaybeJson(child?.jsonQueryResult);
  const spuid = (jq && (jq.spuid || getNested(jq, 'spuid'))) || child?.spuid || child?.skuid || '';
  const shopName = getNested(jq, 'shopInfo.shopName') || child?.shopName || '';
  const shopId = getNested(jq, 'shopInfo.shopId') || child?.shopId || '';
  const productUrl = jq?.materialUrl || jq?.url || child?.materialUrl || child?.productUrl || '';
  const productImage = getNested(jq, 'imageInfo.mainImage') || child?.productImage || '';
  const price = child?.firstPrice || getNested(jq, 'priceInfo.lowestCouponPrice') || getNested(jq, 'priceInfo.price') || '';
  const commissionInfo = getNested(jq, 'commissionInfo.commissionShare') ? `${getNested(jq, 'commissionInfo.commissionShare')}%` : (getNested(jq, 'commissionInfo.commission') || '');
  return {
    skuid: spuid,
    productName: child?.skuName || child?.productName || '',
    shopName,
    shopId,
    productUrl,
    productImage,
    price,
    commissionInfo,
    productId: pub.productId,
    productStatus: pub.productStatus,
    remark: `自动添加 - 发品时间: ${new Date().toLocaleString()}${pub.outerId ? `, 商家编码: ${pub.outerId}` : ''}`
  };
}

export async function addToFavoritesAfterPublishFromTransfer(product, res) {
  const pub = parsePublishResponse(res);
  const spuid = product?.spuid || product?.skuId || product?.skuid || '';
  if (!spuid) return { success: false, reason: 'no_spuid' };
  try {
    const exist = await getBySkuid(spuid);
    if (exist && exist.data) return { success: true, skipped: true };
  } catch(e) {}
  const payload = buildFavoriteFromTransfer(product, pub);
  const addRes = await addToFavorites(payload);
  return { success: addRes && addRes.code === 200 };
}

export async function addToFavoritesAfterPublishFromXb(child, res) {
  const pub = parsePublishResponse(res);
  const jq = parseMaybeJson(child?.jsonQueryResult);
  const spuid = (jq && (jq.spuid || getNested(jq, 'spuid'))) || child?.spuid || child?.skuid || '';
  if (!spuid) return { success: false, reason: 'no_spuid' };
  try {
    const exist = await getBySkuid(spuid);
    if (exist && exist.data) return { success: true, skipped: true };
  } catch(e) {}
  const payload = buildFavoriteFromXb(child, pub);
  const addRes = await addToFavorites(payload);
  return { success: addRes && addRes.code === 200 };
}


