import { writable } from 'svelte/store';
import type { Writable } from 'svelte/store';
import { MissingCustomScalarException } from '@magidoc/plugin-query-generator';
import type { GraphQLObjectType } from 'graphql';
import _ from 'lodash';

export type GeneratedCode = {
  jsCode: string | null;
  pythonCode: string | null;
};

const currentCode: Writable<GeneratedCode> = writable();

const generateQuery = ({
  type,
}: {
  type: GraphQLObjectType;
}): GeneratedCode => {
  try {
    return {
      jsCode: `client
  .upsertNodes('${type.name}', [
    {
      externalId: '${type.name}-1',
      // any additional properties (missing required property will throw error)
    },
  ])
  .then((res) => {
    console.log(res);
  });
`,
      pythonCode: '',
    };
  } catch (error) {
    if (error instanceof MissingCustomScalarException) {
      throw new Error(`
Cannot generate a random value for scalar '${error.type.name}'. 
The random generator is not able to randomly generate a value for non-standard GraphQL scalars. 
You have to provide a custom factory by providing this in your magidoc config:
{
  website: {
    options: {
      queryGenerationFactories: {
        '${error.type.name}': '<an-example-of-scalar-value>'
      }
    }
  }
}

To learn more about how to generate a custom scalar value, see: https://magidoc-org.github.io/magidoc/cli/magidoc-configuration#querygenerationfactories
`);
    }
    throw error;
  }
};

export const upsertCode = {
  subscribe: currentCode.subscribe,
  setField: (type: GraphQLObjectType) =>
    currentCode.update((current) =>
      generateQuery({
        type,
      })
    ),
};
