import {derived, writable} from "svelte/store";
import {EventRepo} from "./event.js";
import {FightRepo} from "./fight.js";
import {PermsRepo} from "./perms.js";
import {PageRepo} from "./page.ts";
import {DataRepo} from "./data.ts";

import { AES, enc, format } from "crypto-js";
import {SchematicRepo} from "./schem.ts";
import {StatsRepo} from "./stats.ts";

export { EventRepo } from "./event.js"

export const apiUrl = import.meta.env.PUBLIC_API_SERVER;
const secret = import.meta.env.PUBLIC_SECRET;

function encryptToken(token: string): string {
    return AES.encrypt(token, secret).toString();
}

function decryptToken(token: string): string {
    return AES.decrypt(token, secret).toString(enc.Utf8);
}

export const fetchWithToken = (token: string, url: string, params: RequestInit = {}) => fetch(`${apiUrl}${url}`, {...params, headers: {...(token !== "" ? {"Authorization": "Bearer " + (token)}:{}), "Content-Type": "application/json", ...params.headers}});
export const tokenStore = writable(decryptToken(localStorage.getItem("sw-session") ?? ""))
tokenStore.subscribe((value) => localStorage.setItem("sw-session", encryptToken(value)))

export const eventRepo = derived(tokenStore, ($token) => new EventRepo($token))
export const fightRepo = derived(tokenStore, ($token) => new FightRepo($token))
export const permsRepo = derived(tokenStore, ($token) => new PermsRepo($token))
export const pageRepo = derived(tokenStore, ($token) => new PageRepo($token))
export const dataRepo = derived(tokenStore, ($token) => new DataRepo($token))
export const schemRepo = derived(tokenStore, ($token) => new SchematicRepo($token))
export const statsRepo = derived(tokenStore, ($token) => new StatsRepo($token))
