// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import schema from "../gql/minifiedSchema.json";

import { devtoolsExchange } from "@urql/devtools";
import { cacheExchange } from "@urql/exchange-graphcache";
import { Client, fetchExchange } from "@urql/vue";

export const graphqlClient = new Client({
  url: import.meta.env.VITE_GRAPHQL_URL || "/server/graphql/",
  exchanges: [
    devtoolsExchange,
    cacheExchange({
      schema: schema,
      updates: {
        Mutation: {
          // eslint-disable-next-line @typescript-eslint/no-unused-vars
          upsert_assignment_completion(result, args, cache, info) {
            // will run on every mutation
            // console.log("udpates upsert_assignment_completion", result);
          },
        },
      },
      optimistic: {
        // @ts-ignore, weiss oh nöt...
        upsert_assignment_completion(args, cache, info) {
          console.log("optimistic upsert_assignment_completion", args, cache, info);
          const id = info.variables.id;
          if (id) {
            const completionData = cache.resolve(
              { __typename: "AssignmentCompletionType", id: "1" },
              "completion_data"
            );
            return {
              __typename: "AssignmentCompletionMutation",
              assignment_completion: {
                __typename: "AssignmentCompletionType",
                id: id,
                completion_data: Object.assign(
                  {},
                  completionData,
                  // @ts-ignore, weiss oh nöt...
                  JSON.parse(args.completion_data_string || "{}")
                ),
                completion_status: args.completion_status,
                evaluation_grade: args.evaluation_grade,
                evaluation_points: args.evaluation_points,
              },
            };
          }
        },
      },
    }),
    fetchExchange,
  ],
});
