import getStorage from "./storage";

const storage = getStorage();
const STORES_KEY = 'stores';

export async function getStores(): Promise<string[]> {
    return (await storage.getData<string[]>(STORES_KEY)) ?? [];
}

export async function addStore(name: string, heslo: string): Promise<string[]> {
    const adminPassword = process.env.ADMIN_PASSWORD;
    if (!adminPassword || heslo !== adminPassword) {
        throw new Error('UNAUTHORIZED');
    }
    const trimmed = name.trim();
    if (!trimmed) {
        throw new Error('Název obchodu nesmí být prázdný');
    }
    const stores = await getStores();
    if (stores.some(s => s.toLowerCase() === trimmed.toLowerCase())) {
        throw new Error('Obchod s tímto názvem již existuje');
    }
    const updated = [...stores, trimmed];
    await storage.setData(STORES_KEY, updated);
    return updated;
}

export async function removeStore(name: string, heslo: string): Promise<string[]> {
    const adminPassword = process.env.ADMIN_PASSWORD;
    if (!adminPassword || heslo !== adminPassword) {
        throw new Error('UNAUTHORIZED');
    }
    const stores = await getStores();
    const updated = stores.filter(s => s.toLowerCase() !== name.trim().toLowerCase());
    await storage.setData(STORES_KEY, updated);
    return updated;
}
