"use client";

/**
 * AppStorage 完整实现（基于 unstorage 抽象）
 *
 * 对齐 Dart 端 `AppStorage`（lib/data/services/storage/app_storage.dart）：
 *   - PWA 对话框一次性展示 / PWA 事件每日上报 / app-info 每日上报
 *
 * 注意：Dart 端是 `static class` 没有接口，本 TS 版本同样保持静态方法风格。
 * 通过 SpAsyncUtil 静态类访问底层存储（浏览器 localStorage / SSR memory 自动切换）。
 *
 * PWA 对话框使用布尔标记；每日上报类方法仍使用 `yyyy-MM-dd` 字符串比对。
 */

import { Result, type Result as ResultT } from "@/utils/result";
import { SpAsyncUtil } from "@/utils/storage";
import { StorageKeys } from "../storage_keys";

export class AppStorage {
  // ---- PWA install dialog ----

  static async canShowPwaDialog(): Promise<ResultT<boolean>> {
    const shownResult = await SpAsyncUtil.getBool(StorageKeys.pwaDialogShown);
    if (!shownResult.success) return shownResult;
    if (shownResult.data === true) return Result.ok(false);
    return Result.ok(true);
  }

  static recordPwaDialogShown(): Promise<ResultT<void>> {
    return SpAsyncUtil.setBool(StorageKeys.pwaDialogShown, true);
  }

  // ---- PWA event reporting ----

  static canReportPwaEvent(todayString: string): Promise<ResultT<boolean>> {
    return AppStorage.canReportKey(StorageKeys.lastPwaEventReported, todayString);
  }

  static recordPwaEventReported(todayString: string): Promise<ResultT<void>> {
    return SpAsyncUtil.setString(StorageKeys.lastPwaEventReported, todayString);
  }

  // ---- app info reporting ----

  static canReportAppInfo(todayString: string): Promise<ResultT<boolean>> {
    return AppStorage.canReportKey(StorageKeys.lastAppInfoReported, todayString);
  }

  static recordAppInfoReported(todayString: string): Promise<ResultT<void>> {
    return SpAsyncUtil.setString(StorageKeys.lastAppInfoReported, todayString);
  }

  // ---- first recharge offer banner ----

  static async getFirstRechargeOfferBannerDismissed(
    userId: string | null | undefined,
  ): Promise<ResultT<boolean>> {
    const r = await SpAsyncUtil.getBool(
      AppStorage.firstRechargeOfferBannerDismissedKey(userId),
    );
    if (!r.success) return r;
    return Result.ok(r.data === true);
  }

  static recordFirstRechargeOfferBannerDismissed(
    userId: string | null | undefined,
  ): Promise<ResultT<void>> {
    return SpAsyncUtil.setBool(
      AppStorage.firstRechargeOfferBannerDismissedKey(userId),
      true,
    );
  }

  // ---- internal helpers ----

  /**
   * 通用"每日一次"判断：
   *   - 取已记录的日期字符串
   *   - 缺失 → 允许（true）
   *   - 等于 today → 拒绝（false）
   *   - 不等于 today → 允许（true）
   */
  private static async canReportKey(
    key: string,
    todayString: string,
  ): Promise<ResultT<boolean>> {
    const r = await SpAsyncUtil.getString(key);
    if (!r.success) return r;
    return Result.ok(r.data === null || r.data !== todayString);
  }

  private static firstRechargeOfferBannerDismissedKey(
    userId: string | null | undefined,
  ): string {
    return `${StorageKeys.firstRechargeOfferBannerDismissed}:${
      userId || "anonymous"
    }`;
  }
}
