import { beforeEach, describe, expect, it } from "vitest";
import { createStorage } from "unstorage";
import memoryDriver from "unstorage/drivers/memory";

import { GuestChatQuota } from "@/data/dto/chat/guest_chat_quota";
import { StorageKeys } from "@/data/storage/storage_keys";
import { todayString, SpAsyncUtil } from "@/utils";

import { ChatStorage } from "../chat_storage";

describe("ChatStorage guest quota", () => {
  beforeEach(() => {
    SpAsyncUtil.setStorage(createStorage({ driver: memoryDriver() }));
    ChatStorage._resetForTests();
  });

  it("keeps an existing daily quota for the current day", async () => {
    const storage = ChatStorage.getInstance();
    await storage.setGuestDailyChatQuota(2, todayString());

    const result = await storage.getGuestDailyChatQuota();

    expect(result.success).toBe(true);
    expect(result.success ? result.data : null).toEqual({
      remaining: 2,
      date: todayString(),
    });
  });

  it("resets daily quota only when the stored date is not today", async () => {
    const storage = ChatStorage.getInstance();
    await storage.setGuestDailyChatQuota(1, "2000-01-01");

    const result = await storage.getGuestDailyChatQuota();

    expect(result.success).toBe(true);
    expect(result.success ? result.data : null).toEqual({
      remaining: GuestChatQuota.threshold,
      date: todayString(),
    });
  });

  it("does not overwrite invalid daily quota data with the default value", async () => {
    await SpAsyncUtil.setString(StorageKeys.guestChatQuota, "{not-json");

    const result = await ChatStorage.getInstance().getGuestDailyChatQuota();
    const stored = await SpAsyncUtil.getString(StorageKeys.guestChatQuota);

    expect(result.success).toBe(false);
    expect(stored.success ? stored.data : null).toBe("{not-json");
  });

  it("does not overwrite invalid total quota data with the default value", async () => {
    await SpAsyncUtil.setString(StorageKeys.guestTotalQuotaRemaining, "{not-json");

    const result = await ChatStorage.getInstance().getGuestTotalQuota();
    const stored = await SpAsyncUtil.getString(StorageKeys.guestTotalQuotaRemaining);

    expect(result.success).toBe(false);
    expect(stored.success ? stored.data : null).toBe("{not-json");
  });
});
