import * as SecureStore from "expo-secure-store";
import { clearSession, readSession, saveSession } from "../../src/services/tokenStorage";
import type { MobileUser } from "../../src/types/auth";

const user: MobileUser = {
  id: 1,
  email: "a@b.c",
  name: "Alice",
  role: "tech",
  user_type: "technicien",
};

describe("tokenStorage", () => {
  beforeEach(() => {
    jest.clearAllMocks();
  });

  describe("saveSession", () => {
    it("stocke access, refresh et user dans SecureStore", async () => {
      await saveSession("acc", "ref", user);
      expect(SecureStore.setItemAsync).toHaveBeenCalledWith("cc_access_token", "acc");
      expect(SecureStore.setItemAsync).toHaveBeenCalledWith("cc_refresh_token", "ref");
      expect(SecureStore.setItemAsync).toHaveBeenCalledWith("cc_user", JSON.stringify(user));
    });
  });

  describe("readSession", () => {
    it("retourne tokens + user parse depuis SecureStore", async () => {
      (SecureStore.getItemAsync as jest.Mock)
        .mockResolvedValueOnce("acc")
        .mockResolvedValueOnce("ref")
        .mockResolvedValueOnce(JSON.stringify(user));

      const session = await readSession();
      expect(session.accessToken).toBe("acc");
      expect(session.refreshToken).toBe("ref");
      expect(session.user).toEqual(user);
    });

    it("user=null quand aucun user stocke", async () => {
      (SecureStore.getItemAsync as jest.Mock)
        .mockResolvedValueOnce(null)
        .mockResolvedValueOnce(null)
        .mockResolvedValueOnce(null);

      const session = await readSession();
      expect(session.user).toBeNull();
    });

    it("user=null quand user stocke corrompu", async () => {
      (SecureStore.getItemAsync as jest.Mock)
        .mockResolvedValueOnce("acc")
        .mockResolvedValueOnce("ref")
        .mockResolvedValueOnce("{not-json");

      const session = await readSession();
      expect(session.user).toBeNull();
    });
  });

  describe("clearSession", () => {
    it("supprime les 3 cles", async () => {
      await clearSession();
      expect(SecureStore.deleteItemAsync).toHaveBeenCalledWith("cc_access_token");
      expect(SecureStore.deleteItemAsync).toHaveBeenCalledWith("cc_refresh_token");
      expect(SecureStore.deleteItemAsync).toHaveBeenCalledWith("cc_user");
    });
  });
});
