// =============================================================
// storage.jsx — LocalStorage ユーティリティ
// =============================================================

const STORAGE_KEY = 'fsi_poc_data_v3';

const _buildDefault = () => ({
  role:          'field',
  currentUserId: 1,
  ...window.generateSampleData(),
  correctionPhotos: [],
  ngPhotos:         [],
});

const StorageUtils = {
  _load() {
    try {
      const raw = localStorage.getItem(STORAGE_KEY);
      return raw ? JSON.parse(raw) : null;
    } catch (e) {
      console.warn('[FSI] localStorage 読み込み失敗:', e);
      return null;
    }
  },

  _save(data) {
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
    } catch (e) {
      console.warn('[FSI] localStorage 書き込み失敗:', e);
    }
  },

  /** 初回起動時にサンプルデータを seed する */
  init() {
    let data = this._load();
    if (!data) {
      data = _buildDefault();
      this._save(data);
      console.info('[FSI] サンプルデータを初期化しました');
    } else if (!data.incidentReports) {
      // マイグレーション: incidentReports を追加
      const { incidentReports } = window.generateSampleData();
      data = { ...data, incidentReports };
      this._save(data);
      console.info('[FSI] incidentReports をマイグレーションしました');
    }
    return data;
  },

  /** 現在のデータを取得 */
  get() {
    return this._load() || this.init();
  },

  /** 部分更新（updaterFn は data => newData） */
  update(updaterFn) {
    const current = this.get();
    const next    = updaterFn(current);
    this._save(next);
    return next;
  },

  /** 全クリア → サンプルデータで再初期化 */
  clear() {
    localStorage.removeItem(STORAGE_KEY);
    const fresh = _buildDefault();
    this._save(fresh);
    console.info('[FSI] データをリセットしました');
    return fresh;
  },

  /** データサマリーを返す（デバッグ用） */
  summary() {
    const d = this.get();
    return {
      checkRecords:      (d.checkRecords      || []).length,
      checkResults:      (d.checkResults      || []).length,
      ngDetails:         (d.ngDetails         || []).length,
      correctionOrders:  (d.correctionOrders  || []).length,
      correctionReports: (d.correctionReports || []).length,
    };
  },
};

Object.assign(window, { StorageUtils });
