import { DEFAULT_MATERIALS, MATERIALS_KEY, OFFERS_KEY } from "../constants/pvc";

export function loadOffers() {
  try {
    const raw = localStorage.getItem(OFFERS_KEY);
    if (!raw) return [];
    const parsed = JSON.parse(raw);
    return Array.isArray(parsed) ? parsed : [];
  } catch {
    return [];
  }
}

export function saveOffers(offers) {
  try {
    localStorage.setItem(OFFERS_KEY, JSON.stringify(offers));
  } catch {}
}

export function loadMaterials() {
  try {
    const raw = localStorage.getItem(MATERIALS_KEY);
    if (!raw) return DEFAULT_MATERIALS;
    const parsed = JSON.parse(raw);
    return {
      profiles: Array.isArray(parsed?.profiles) && parsed.profiles.length ? parsed.profiles : DEFAULT_MATERIALS.profiles,
      irons: Array.isArray(parsed?.irons) && parsed.irons.length ? parsed.irons : DEFAULT_MATERIALS.irons,
      glassTypes:
        Array.isArray(parsed?.glassTypes) && parsed.glassTypes.length ? parsed.glassTypes : DEFAULT_MATERIALS.glassTypes,
      accessories: Array.isArray(parsed?.accessories) ? parsed.accessories : DEFAULT_MATERIALS.accessories,
    };
  } catch {
    return DEFAULT_MATERIALS;
  }
}

export function saveMaterials(materials) {
  try {
    localStorage.setItem(MATERIALS_KEY, JSON.stringify(materials));
  } catch {}
}

/** migration: old offers may have profileName/ironName or profile fields */
export function migrateOffers(existingOffers, materials) {
  const profileByName = new Map(materials.profiles.map((p) => [p.name, p.id]));
  const ironByName = new Map(materials.irons.map((i) => [i.name, i.id]));
  const defaultProfileId = materials.profiles[0]?.id || "profile-1";
  const defaultIronId = materials.irons[0]?.id || "iron-1";

  return (existingOffers || []).map((o) => {
    const profileId = o.profileId || profileByName.get(o.profileName) || profileByName.get(o.profile) || defaultProfileId;
    const ironId = o.ironId || ironByName.get(o.ironName) || ironByName.get(o.iron) || defaultIronId;

    return {
      ...o,
      profileId,
      ironId,
      updatedAt: o.updatedAt || Date.now(),
      createdAt: o.createdAt || Date.now(),
      positions: Array.isArray(o.positions) ? o.positions : [],
    };
  });
}
