import { caseInsensitiveEqual as e } from "../../functions/utils/caseInsensitive.utils.mjs";
import { isValidOldStylePrivateAddress as t, isValidPrivateAddress as n } from "../../functions/utils/addresses.mjs";
import { Logger as r } from "../../error-handling/logger.mjs";
import "../../functions/index.mjs";
import { get as i, update as a } from "idb-keyval";
var o = 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 a(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 {
			await this.removeOldStylePrivateAddressContacts(e);
			let t = e.toLowerCase(), n = await i(this.STORAGE_KEY);
			return !n || !n[t] ? [] : n[t];
		} catch (e) {
			return r.error("Error while getting contacts:", e), [];
		}
	}
	async editContact(t, n, r) {
		let i = t.toLowerCase();
		await a(this.STORAGE_KEY, (t) => {
			let a = t ?? {}, o = a[i];
			if (!a || !o) throw Error("Contacts could not be fetched");
			this.checkForDuplicate(o, r, 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] = r, a[i] = o, a;
		});
	}
	async removeOldStylePrivateAddressContacts(e) {
		let r = e.toLowerCase(), i = 0;
		return await a(this.STORAGE_KEY, (e) => {
			let a = e ?? {}, o = a[r];
			if (!o?.length) return a;
			let s = o.filter((e) => {
				let r = e.ethereumAddress;
				return !t(r) || n(r) ? !0 : (i += 1, !1);
			});
			return i === 0 || (a[r] = s), a;
		}), i;
	}
	async deleteContact(e, t) {
		let n = e.toLowerCase();
		await a(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
export { o as contactStorage };
