import { OffersApi } from "../api/offers";
import { PositionsApi } from "../api/positions";
import { normalizeOffer, unwrapCollection } from "./apiNormalize";

/**
 * Helpers
 */
function unwrapApi(respOrData) {
  const data = respOrData?.data ?? respOrData;
  return data?.data ?? data; // supports Laravel Resource {data:{...}} or raw {...}
}

function sanitizePositionsForSync(positions = []) {
  // remove DB helper keys if they exist (keep EVERYTHING else)
  return positions.map((p) => {
    const { _db_id, offer_id, ...rest } = p || {};
    return rest;
  });
}

/**
 * Fetch offers from DB (paginated) and convert to UI shape.
 */
export async function fetchOffers() {
  const resp = await OffersApi.list({ per_page: 200 });
  const rows = unwrapCollection(resp.data);
  return rows.map(normalizeOffer);
}

export async function fetchOffer(id) {
  const resp = await OffersApi.get(id);
  return normalizeOffer(unwrapApi(resp));
}

export async function createOffer(uiOffer) {
  const { positions = [], ...offerOnly } = uiOffer;

  // 1) create offer
  const resp = await OffersApi.create(offerOnly);
  const savedOffer = unwrapApi(resp);

  // 2) sync positions (full objects)
  const cleanPositions = sanitizePositionsForSync(positions);
  await PositionsApi.sync(savedOffer.id, cleanPositions);

  return { ...normalizeOffer(savedOffer), positions };
}

export async function updateOffer(uiOffer) {
  const { positions = [], ...offerOnly } = uiOffer || {};

  // ✅ accept id from different shapes (id / offerId / offer.id)
  const offerId =
    offerOnly.id ??
    offerOnly.offerId ??
    uiOffer?.offer?.id ??
    uiOffer?.id;

  if (!offerId) {
    console.error("updateOffer(): missing offerId", uiOffer);
    throw new Error("Cannot update offer: missing id");
  }

  // 1) update offer itself
  const resp = await OffersApi.update(offerId, offerOnly);
  const savedOffer = resp?.data?.data ?? resp?.data ?? resp;

  // 2) sync positions (full objects)
  await PositionsApi.sync(offerId, sanitizePositionsForSync(positions));

  return { ...(savedOffer?.data ? savedOffer.data : savedOffer), positions };
}


export async function deleteOffer(id) {
  await OffersApi.remove(id);
}

export async function dbFetchPositions(offerId) {
  const resp = await PositionsApi.list(offerId);
  return unwrapApi(resp); // your backend returns expanded objects
}
