import { redirect } from '@sveltejs/kit';
import { api } from '$lib/api';
import { getStoredClientSession, hasStoredAdminSession, hasStoredClientSession } from '$lib/session';
import { canOpenClientAccess, getWorkspaceHomeHref } from '$lib/workspace-access';

function emptyPayload() {
  return {
    clients: [],
    exportPreview: {
      generated_at: '',
      client_rows: [],
      user_rows: [],
      feature_rows: [],
      permission_rows: [],
      audit_rows: [],
      clients: []
    }
  };
}

export async function load({ fetch }) {
  if (!hasStoredAdminSession() && !hasStoredClientSession()) {
    return emptyPayload();
  }

  if (hasStoredClientSession()) {
    const session = getStoredClientSession();
    if (session && !canOpenClientAccess(session)) {
      throw redirect(307, getWorkspaceHomeHref(session));
    }
  }

  try {
    const [clients, exportPreview] = await Promise.all([api.clientAccess(fetch), api.clientAccessExport(fetch)]);
    return { clients, exportPreview };
  } catch {
    return emptyPayload();
  }
}
