import { optima } from "$lib";
import { handleApiError } from "$lib/optima-api/errorHandler";
import { checkPermissions, type PermissionMap } from "$lib/permissions";
import type { PageServerLoad } from "./$types";

export const load: PageServerLoad = async ({ locals, params }) => {
  const accessToken = locals.session?.accessToken;
  if (!accessToken) {
    return {
      opportunity: null,
      notes: [],
      contacts: [],
      products: [],
      quotes: [],
      accessToken: null,
      permissions: {} as PermissionMap,
      workflowStatus: null,
    };
  }

  try {
    const [result, permissions, workflowResult, opportunityTypesResult] = await Promise.all([
      optima.sales.fetchOne(accessToken, params.id, [
        "notes",
        "contacts",
        "products",
        "quotes",
      ]),
      checkPermissions(accessToken, [
        "sales.opportunity.fetch",
        "sales.opportunity.refresh",
        "sales.opportunity.note.create",
        "sales.opportunity.note.update",
        "sales.opportunity.note.delete",
        "sales.opportunity.quote.fetch",
        "sales.opportunity.quote.commit",
        "sales.opportunity.quote.commit.backgenerate",
        "sales.opportunity.quote.preview",
        "sales.opportunity.quote.download",
        "sales.opportunity.quote.fetch_downloads",
        "sales.opportunity.view_margin",
        "sales.opportunity.view_cost",
        "sales.opportunity.view_profit",
        "sales.opportunity.update",
        "sales.opportunity.delete",
        "sales.opportunity.product.delete",
        "sales.opportunity.product.update",
        "sales.opportunity.workflow",
        "sales.opportunity.finalize",
        "sales.opportunity.cancel",
        "sales.opportunity.review",
        "sales.opportunity.send",
        "sales.opportunity.reopen",
        "sales.opportunity.win",
        "sales.opportunity.lose",
        "ui.navigation.reports.view",
      ]),
      optima.sales.fetchWorkflowStatus(accessToken, params.id).catch((err) => {
        console.error("[Workflow] Failed to load workflow status:", err);
        return null;
      }),
      optima.sales.fetchOpportunityTypes(accessToken).catch(() => ({ data: [] })),
    ]);

    const { writeFileSync } = await import("fs");
    const { resolve } = await import("path");
    writeFileSync(
      resolve("opportunity-debug.json"),
      JSON.stringify(result, null, 2),
    );

    console.log("[page.server] Full API response:", JSON.stringify(result, null, 2));

    const opportunity = result?.data ?? null;
    const notes = result?.data?.notes ?? [];
    const contacts = result?.data?.contacts ?? [];
    const products = result?.data?.products ?? [];
    const quotes = result?.data?.quotes ?? [];
    const workflowStatus = workflowResult?.data ?? null;

    return {
      opportunity,
      opportunityId: params.id,
      notes,
      contacts,
      products,
      quotes,
      accessToken,
      permissions,
      workflowStatus,
      opportunityTypes: opportunityTypesResult?.data ?? [],
    };
  } catch (err) {
    handleApiError(err);
  }
};
