// Live snapshot of the per-user storage quota. Refreshed on app start, after every
// upload completes, and whenever the account page mounts. Mirrors backend
// `handlers::me::QuotaDto`.
//
// `enabled = false` means quota enforcement is currently off in admin config; the UI
// hides the widget entirely in that case.

import { writable } from 'svelte/store';
import { api } from './api';
import { onClearAuth } from './auth';

export interface QuotaSnapshot {
	enabled: boolean;
	used_bytes: number;
	limit_bytes: number | null;
	active_uploaders: number;
	free_disk_bytes: number;
}

const empty: QuotaSnapshot = {
	enabled: false,
	used_bytes: 0,
	limit_bytes: null,
	active_uploaders: 0,
	free_disk_bytes: 0
};

export const quotaStore = writable<QuotaSnapshot>(empty);

// Reset on logout, the same way role-store / ban-store / upload-queue do. A phone handed
// round a party is one browser profile: `goto()` is a client-side navigation, so no module
// re-imports and no `onMount` re-runs, and without this the next guest saw the PREVIOUS
// guest's storage usage — their data, on their screen — until the first refresh landed.
onClearAuth(() => quotaStore.set(empty));

/** Refresh from the server. Swallows errors so a transient network blip doesn't
 *  break the account page; the previous snapshot just stays in place. */
export async function refreshQuota(): Promise<void> {
	try {
		const snap = await api.get<QuotaSnapshot>('/me/quota');
		quotaStore.set(snap);
	} catch {
		// keep previous snapshot
	}
}
