/**
 * 游客每日聊天配额数据 DTO
 */
import {
  GuestChatQuotaSchema,
  type GuestChatQuotaInput,
  type GuestChatQuotaData,
} from "@/data/schemas/chat/guest_chat_quota";
import { AppEnvUtil } from "@/utils";

export class GuestChatQuota {
  // 静态常量
  static readonly maxQuotaPerDay = 40;
  static readonly maxQuotaPerDayTest = 4;

  static readonly defaultTotalQuota = 50;
  static readonly defaultTotalQuotaTest = 5;
  static readonly quotaExhausted = 0;

  declare readonly remaining: number;
  declare readonly date: string;

  private constructor(input: GuestChatQuotaInput) {
    const data = GuestChatQuotaSchema.parse(input);
    Object.assign(this, data);
    Object.freeze(this);
  }

  static from(input: GuestChatQuotaInput): GuestChatQuota {
    return new GuestChatQuota(input);
  }

  static fromJson(json: unknown): GuestChatQuota {
    return GuestChatQuota.from(json as GuestChatQuotaInput);
  }

  /**
   * 配额耗尽状态值
   */
  static get exhausted(): number {
    return GuestChatQuota.quotaExhausted;
  }

  /**
   * 获取当前环境的每日最大配额
   */
  static get threshold(): number {
    return AppEnvUtil.isProduction()
      ? GuestChatQuota.maxQuotaPerDay
      : GuestChatQuota.maxQuotaPerDayTest;
  }

  /**
   * 获取当前环境的总配额默认值
   */
  static get totalQuotaDefault(): number {
    return AppEnvUtil.isProduction()
      ? GuestChatQuota.defaultTotalQuota
      : GuestChatQuota.defaultTotalQuotaTest;
  }

  /**
   * 创建初始配额实例
   */
  static initial(todayString: string): GuestChatQuota {
    return new GuestChatQuota({
      remaining: GuestChatQuota.threshold,
      date: todayString,
    });
  }

  /**
   * 是否需要重置（跨天）
   */
  needsReset(todayString: string): boolean {
    return this.date !== todayString;
  }

  toJson(): GuestChatQuotaData {
    return GuestChatQuotaSchema.parse(this);
  }
}
