import { readBody } from "h3";
import { graphql } from "graphql";
import { getAuthContext } from "../utils/auth";
import { crmGraphqlRoot, crmGraphqlSchema } from "../graphql/schema";

type GraphqlBody = {
  query?: string;
  operationName?: string;
  variables?: Record<string, unknown>;
};

export default defineEventHandler(async (event) => {
  const body = await readBody<GraphqlBody>(event);

  if (!body?.query || !body.query.trim()) {
    throw createError({ statusCode: 400, statusMessage: "GraphQL query is required" });
  }

  let auth = null;
  try {
    auth = await getAuthContext(event);
  } catch {
    auth = null;
  }

  const result = await graphql({
    schema: crmGraphqlSchema,
    source: body.query,
    rootValue: crmGraphqlRoot,
    contextValue: { auth, event },
    variableValues: body.variables,
    operationName: body.operationName,
  });

  return {
    data: result.data ?? null,
    errors: result.errors?.map((error) => ({ message: error.message })) ?? undefined,
  };
});
