import { readJson, writeJson } from "./storage";
import { KEYS } from "../data/mock/keys";

export type ScoutTodayState = {
  /** YYYY-MM-DD local */
  date: string;
  done: number;
  goalActivity: number;
  goalValue: number;
};

function todayKey(): string {
  const d = new Date();
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");
  return `${y}-${m}-${day}`;
}

export function loadScoutToday(): ScoutTodayState {
  const raw = readJson<ScoutTodayState | null>(KEYS.scoutToday, null);
  const date = todayKey();
  if (!raw || raw.date !== date) {
    return {
      date,
      done: 0,
      goalActivity: 20,
      goalValue: 8,
    };
  }
  return {
    date,
    done: Math.max(0, raw.done || 0),
    goalActivity: Math.max(1, raw.goalActivity || 20),
    goalValue: Math.max(1, raw.goalValue || 8),
  };
}

export function saveScoutToday(state: ScoutTodayState): void {
  writeJson(KEYS.scoutToday, {
    ...state,
    date: todayKey(),
  });
}

export function bumpScoutTodayDone(n = 1): ScoutTodayState {
  const cur = loadScoutToday();
  const next = { ...cur, date: todayKey(), done: cur.done + n };
  saveScoutToday(next);
  return next;
}
