import { caseInsensitiveEqual as e } from "../../functions/utils/caseInsensitive.utils.mjs";
import { Logger as t } from "../../error-handling/logger.mjs";
import "../../functions/index.mjs";
import { get as n, update as r } from "idb-keyval";
new class {
	STORAGE_KEY = "contacts";
	checkForDuplicate(e, t, n) {
		if (e.find(({ ethereumAddress: e, nickname: r }) => (e === t.ethereumAddress || r === t.nickname) && e !== n) !== void 0) throw Error("Duplicate Contact attribute");
	}
	async createContact(e, t) {
		let n = e.toLowerCase();
		await r(this.STORAGE_KEY, (e) => {
			let r = e ?? {}, i = r[n] ?? [];
			return this.checkForDuplicate(i, t), i.push(t), r[n] = i, r;
		});
	}
	async getContacts(e) {
		try {
			let t = e.toLowerCase(), r = await n(this.STORAGE_KEY);
			return !r || !r[t] ? [] : r[t];
		} catch (e) {
			return t.error("Error while getting contacts:", e), [];
		}
	}
	async editContact(t, n, i) {
		let a = t.toLowerCase();
		await r(this.STORAGE_KEY, (t) => {
			let r = t ?? {}, o = r[a];
			if (!r || !o) throw Error("Contacts could not be fetched");
			this.checkForDuplicate(o, i, n);
			let s = o.findIndex(({ ethereumAddress: t }) => e(t, n));
			if (s === -1) throw Error("Contact to be edited was not found");
			return o[s] = i, r[a] = o, r;
		});
	}
	async deleteContact(e, t) {
		let n = e.toLowerCase();
		await r(this.STORAGE_KEY, (e) => {
			let r = e ?? {}, i = r[n];
			if (!r || !i) throw Error("Contacts could not be fetched");
			return r[n] = i.filter(({ ethereumAddress: e }) => e !== t), r;
		});
	}
}();
//#endregion
