import { describe, expect, test } from "bun:test";
import {
	USER_SETTINGS_STORAGE_KEY,
	getDefaultUserSettings,
	loadUserSettings,
	saveUserSettings,
	type UserSettings,
} from "@/lib/user-settings";

const createStorage = (initialState?: Record<string, string>) => {
	const state = { ...initialState };

	return {
		getItem(key: string) {
			return state[key] ?? null;
		},
		setItem(key: string, value: string) {
			state[key] = value;
		},
		read(key: string) {
			return state[key];
		},
	};
};

const createFailingStorage = () => ({
	getItem() {
		throw new Error("storage read failed");
	},
	setItem() {
		throw new Error("storage write failed");
	},
});

describe("user settings defaults", () => {
	test("returns typed defaults for future feature flags", () => {
		expect(getDefaultUserSettings()).toEqual({
			aiEnabled: true,
			skipAiReview: false,
		});
	});

	test("loads defaults when no persisted settings exist yet", () => {
		const storage = createStorage();

		expect(loadUserSettings(storage)).toEqual(getDefaultUserSettings());
	});

	test("loads the saved values from shared persisted settings storage", () => {
		const savedSettings: UserSettings = {
			aiEnabled: false,
			skipAiReview: true,
		};
		const storage = createStorage({
			[USER_SETTINGS_STORAGE_KEY]: JSON.stringify(savedSettings),
		});

		expect(loadUserSettings(storage)).toEqual(savedSettings);
	});

	test("keeps defaults for missing or malformed saved fields", () => {
		const storage = createStorage({
			[USER_SETTINGS_STORAGE_KEY]: JSON.stringify({ skipAiReview: true, aiEnabled: "nope" }),
		});

		expect(loadUserSettings(storage)).toEqual({
			aiEnabled: true,
			skipAiReview: true,
		});
	});

	test("falls back to defaults when persisted settings are not valid JSON", () => {
		const storage = createStorage({
			[USER_SETTINGS_STORAGE_KEY]: "{not-json",
		});

		expect(loadUserSettings(storage)).toEqual(getDefaultUserSettings());
	});

	test("falls back to defaults when storage cannot be read", () => {
		expect(loadUserSettings(createFailingStorage())).toEqual(
			getDefaultUserSettings(),
		);
	});

	test("saves a complete settings snapshot under the shared persistence key", () => {
		const storage = createStorage();
		const nextSettings: UserSettings = {
			aiEnabled: false,
			skipAiReview: true,
		};

		expect(saveUserSettings(nextSettings, storage)).toEqual(nextSettings);
		expect(storage.read(USER_SETTINGS_STORAGE_KEY)).toBe(
			JSON.stringify(nextSettings),
		);
	});

	test("returns the requested settings even when persistence fails", () => {
		const nextSettings: UserSettings = {
			aiEnabled: false,
			skipAiReview: true,
		};

		expect(saveUserSettings(nextSettings, createFailingStorage())).toEqual(
			nextSettings,
		);
	});
});
