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

export async function load({ params, fetch }) {
  const mixId = Number(params.id);

  if (!Number.isFinite(mixId)) {
    throw error(404, 'Mix not found');
  }

  if (!hasStoredClientSession()) {
    return {
      mix: null,
      rawMaterials: []
    };
  }

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

  try {
    const [mix, rawMaterials] = await Promise.all([
      api.mix(mixId, fetch),
      hasModuleAccess(session, 'raw_materials') || session?.role === 'internal' ? api.rawMaterials(fetch) : Promise.resolve([])
    ]);

    return {
      mix,
      rawMaterials
    };
  } catch {
    throw error(404, 'Mix not found');
  }
}
