import { create } from "zustand";

const ONE_HOUR = 1000 * 60 * 60;

type MobileUser = {
	id: string;
	name: string;
	role: "user" | "lead" | "manager" | "admin";
	excludedCommand: string[];
	scannerId: string;
};

type AuthState = {
	user: MobileUser | null;
	isUnlocked: boolean;
	lastScanAt: number | null;

	setUser: (user: MobileUser) => void;
	updateLastScan: () => void;
	lock: () => void;
	logout: () => void;
	shouldLockForIdle: () => boolean;
};

export const useMobileAuthStore = create<AuthState>((set, get) => ({
	user: null,
	isUnlocked: false,
	lastScanAt: null,

	setUser: (user) =>
		set({
			user,
			isUnlocked: true,
			lastScanAt: Date.now(),
		}),
	updateLastScan: () => set({ lastScanAt: Date.now() }),
	lock: () => set({ isUnlocked: false }),

	logout: () =>
		set({
			user: null,
			isUnlocked: false,
			lastScanAt: null,
		}),
	shouldLockForIdle: () => {
		const lastScanAt = get().lastScanAt;

		if (!lastScanAt) return true;

		return Date.now() - lastScanAt > ONE_HOUR;
	},
}));
