import { KEYS } from "../data/mock/keys";
import { newId } from "./id";
import { readJson, writeJson } from "./storage";
import { nowUnixNano } from "./time";
import { PLANS, setMemberPrefs, type PlanId } from "./usageMeter";

/** mock 方案購買（接金流前本機假資料） */
export type PlanPurchase = {
  id: string;
  uid: string;
  plan_id: PlanId;
  amount_twd: number;
  /** paid 才視為真正買成 */
  status: "paid" | "failed" | "pending";
  /** 假卡末四碼等 */
  mock_ref?: string;
  created_at: number;
};

function loadPurchases(): PlanPurchase[] {
  return readJson(KEYS.planPurchases, [] as PlanPurchase[]);
}

function savePurchases(list: PlanPurchase[]): void {
  writeJson(KEYS.planPurchases, list.slice(0, 200));
}

export function listPlanPurchases(uid: string, limit = 20): PlanPurchase[] {
  return loadPurchases()
    .filter((p) => p.uid === uid)
    .sort((a, b) => b.created_at - a.created_at)
    .slice(0, limit);
}

/**
 * mock 完成付款：寫入購買紀錄並套用方案。
 * 正式環境應改為金流 webhook 確認後才 setMemberPrefs。
 */
export function mockCompletePlanPurchase(opts: {
  uid: string;
  plan_id: PlanId;
  mock_ref?: string;
}): PlanPurchase {
  const plan = PLANS[opts.plan_id];
  if (!plan) throw new Error("未知方案");

  const rec: PlanPurchase = {
    id: newId("pay"),
    uid: opts.uid,
    plan_id: opts.plan_id,
    amount_twd: plan.price_twd,
    status: "paid",
    mock_ref: opts.mock_ref || "mock",
    created_at: nowUnixNano(),
  };
  const list = loadPurchases();
  list.unshift(rec);
  savePurchases(list);

  // 只有 paid 才改方案
  setMemberPrefs(opts.uid, { plan_id: opts.plan_id });
  return rec;
}
