//
// Copyright 2021 Vulcanize, Inc.
//

import assert from 'assert';
import debug from 'debug';
import { GraphQLResolveInfo } from 'graphql';
import { ExpressContext } from 'apollo-server-express';
import winston from 'winston';

import {
  gqlTotalQueryCount,
  gqlQueryCount,
  gqlQueryDuration,
  getResultState,
  IndexerInterface,
  GraphQLBigInt,
  GraphQLBigDecimal,
  BlockHeight,
  OrderDirection,
  jsonBigIntStringReplacer,
  EventWatcher,
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  setGQLCacheHints
} from '@cerc-io/util';

import { Indexer } from './indexer';

import { RouteProcessor } from './entity/RouteProcessor';
import { Route } from './entity/Route';
import { User } from './entity/User';

const log = debug('vulcanize:resolver');

const executeAndRecordMetrics = async (
  indexer: Indexer,
  gqlLogger: winston.Logger,
  opName: string,
  expressContext: ExpressContext,
  operation: () => Promise<any>
) => {
  gqlTotalQueryCount.inc(1);
  gqlQueryCount.labels(opName).inc(1);
  const endTimer = gqlQueryDuration.labels(opName).startTimer();

  try {
    const [result, syncStatus] = await Promise.all([
      operation(),
      indexer.getSyncStatus()
    ]);

    gqlLogger.info({
      opName,
      query: expressContext.req.body.query,
      variables: expressContext.req.body.variables,
      latestIndexedBlockNumber: syncStatus?.latestIndexedBlockNumber,
      urlPath: expressContext.req.path,
      apiKey: expressContext.req.header('x-api-key'),
      origin: expressContext.req.headers.origin
    });
    return result;
  } catch (error) {
    gqlLogger.error({
      opName,
      error,
      query: expressContext.req.body.query,
      variables: expressContext.req.body.variables,
      urlPath: expressContext.req.path,
      apiKey: expressContext.req.header('x-api-key'),
      origin: expressContext.req.headers.origin
    });

    throw error;
  } finally {
    endTimer();
  }
};

export const createResolvers = async (
  indexerArg: IndexerInterface,
  eventWatcher: EventWatcher,
  gqlLogger: winston.Logger
): Promise<any> => {
  const indexer = indexerArg as Indexer;

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const gqlCacheConfig = indexer.serverConfig.gql.cache;

  return {
    BigInt: GraphQLBigInt,

    BigDecimal: GraphQLBigDecimal,

    Event: {
      __resolveType: (obj: any) => {
        assert(obj.__typename);

        return obj.__typename;
      }
    },

    Subscription: {
      onEvent: {
        subscribe: () => eventWatcher.getEventIterator()
      }
    },

    Mutation: {
      watchContract: async (_: any, { address, kind, checkpoint, startingBlock = 1 }: { address: string, kind: string, checkpoint: boolean, startingBlock: number }): Promise<boolean> => {
        log('watchContract', address, kind, checkpoint, startingBlock);
        await indexer.watchContract(address, kind, checkpoint, startingBlock);

        return true;
      }
    },

    Query: {
      routeProcessor: async (
        _: any,
        { id, block = {} }: { id: string, block: BlockHeight },
        expressContext: ExpressContext,
        info: GraphQLResolveInfo
      ) => {
        log('routeProcessor', id, JSON.stringify(block, jsonBigIntStringReplacer));

        // Set cache-control hints
        // setGQLCacheHints(info, block, gqlCacheConfig);

        return executeAndRecordMetrics(
          indexer,
          gqlLogger,
          'routeProcessor',
          expressContext,
          async () => indexer.getSubgraphEntity(RouteProcessor, id, block, info)
        );
      },

      routeProcessors: async (
        _: any,
        { block = {}, where, first, skip, orderBy, orderDirection }: { block: BlockHeight, where: { [key: string]: any }, first: number, skip: number, orderBy: string, orderDirection: OrderDirection },
        expressContext: ExpressContext,
        info: GraphQLResolveInfo
      ) => {
        log('routeProcessors', JSON.stringify(block, jsonBigIntStringReplacer), JSON.stringify(where, jsonBigIntStringReplacer), first, skip, orderBy, orderDirection);

        // Set cache-control hints
        // setGQLCacheHints(info, block, gqlCacheConfig);

        return executeAndRecordMetrics(
          indexer,
          gqlLogger,
          'routeProcessors',
          expressContext,
          async () => indexer.getSubgraphEntities(
            RouteProcessor,
            block,
            where,
            { limit: first, skip, orderBy, orderDirection },
            info
          )
        );
      },

      route: async (
        _: any,
        { id, block = {} }: { id: string, block: BlockHeight },
        expressContext: ExpressContext,
        info: GraphQLResolveInfo
      ) => {
        log('route', id, JSON.stringify(block, jsonBigIntStringReplacer));

        // Set cache-control hints
        // setGQLCacheHints(info, block, gqlCacheConfig);

        return executeAndRecordMetrics(
          indexer,
          gqlLogger,
          'route',
          expressContext,
          async () => indexer.getSubgraphEntity(Route, id, block, info)
        );
      },

      routes: async (
        _: any,
        { block = {}, where, first, skip, orderBy, orderDirection }: { block: BlockHeight, where: { [key: string]: any }, first: number, skip: number, orderBy: string, orderDirection: OrderDirection },
        expressContext: ExpressContext,
        info: GraphQLResolveInfo
      ) => {
        log('routes', JSON.stringify(block, jsonBigIntStringReplacer), JSON.stringify(where, jsonBigIntStringReplacer), first, skip, orderBy, orderDirection);

        // Set cache-control hints
        // setGQLCacheHints(info, block, gqlCacheConfig);

        return executeAndRecordMetrics(
          indexer,
          gqlLogger,
          'routes',
          expressContext,
          async () => indexer.getSubgraphEntities(
            Route,
            block,
            where,
            { limit: first, skip, orderBy, orderDirection },
            info
          )
        );
      },

      user: async (
        _: any,
        { id, block = {} }: { id: string, block: BlockHeight },
        expressContext: ExpressContext,
        info: GraphQLResolveInfo
      ) => {
        log('user', id, JSON.stringify(block, jsonBigIntStringReplacer));

        // Set cache-control hints
        // setGQLCacheHints(info, block, gqlCacheConfig);

        return executeAndRecordMetrics(
          indexer,
          gqlLogger,
          'user',
          expressContext,
          async () => indexer.getSubgraphEntity(User, id, block, info)
        );
      },

      users: async (
        _: any,
        { block = {}, where, first, skip, orderBy, orderDirection }: { block: BlockHeight, where: { [key: string]: any }, first: number, skip: number, orderBy: string, orderDirection: OrderDirection },
        expressContext: ExpressContext,
        info: GraphQLResolveInfo
      ) => {
        log('users', JSON.stringify(block, jsonBigIntStringReplacer), JSON.stringify(where, jsonBigIntStringReplacer), first, skip, orderBy, orderDirection);

        // Set cache-control hints
        // setGQLCacheHints(info, block, gqlCacheConfig);

        return executeAndRecordMetrics(
          indexer,
          gqlLogger,
          'users',
          expressContext,
          async () => indexer.getSubgraphEntities(
            User,
            block,
            where,
            { limit: first, skip, orderBy, orderDirection },
            info
          )
        );
      },

      events: async (
        _: any,
        { blockHash, contractAddress, name }: { blockHash: string, contractAddress: string, name?: string },
        expressContext: ExpressContext
      ) => {
        log('events', blockHash, contractAddress, name);

        return executeAndRecordMetrics(
          indexer,
          gqlLogger,
          'events',
          expressContext,
          async () => {
            const block = await indexer.getBlockProgress(blockHash);
            if (!block || !block.isComplete) {
              throw new Error(`Block hash ${blockHash} number ${block?.blockNumber} not processed yet`);
            }

            const events = await indexer.getEventsByFilter(blockHash, contractAddress, name);
            return events.map(event => indexer.getResultEvent(event));
          }
        );
      },

      eventsInRange: async (
        _: any,
        { fromBlockNumber, toBlockNumber }: { fromBlockNumber: number, toBlockNumber: number },
        expressContext: ExpressContext
      ) => {
        log('eventsInRange', fromBlockNumber, toBlockNumber);

        return executeAndRecordMetrics(
          indexer,
          gqlLogger,
          'eventsInRange',
          expressContext,
          async () => {
            const syncStatus = await indexer.getSyncStatus();

            if (!syncStatus) {
              throw new Error('No blocks processed yet');
            }

            if ((fromBlockNumber < syncStatus.initialIndexedBlockNumber) || (toBlockNumber > syncStatus.latestProcessedBlockNumber)) {
              throw new Error(`Block range should be between ${syncStatus.initialIndexedBlockNumber} and ${syncStatus.latestProcessedBlockNumber}`);
            }

            const events = await indexer.getEventsInRange(fromBlockNumber, toBlockNumber);
            return events.map(event => indexer.getResultEvent(event));
          }
        );
      },

      getStateByCID: async (
        _: any,
        { cid }: { cid: string },
        expressContext: ExpressContext
      ) => {
        log('getStateByCID', cid);

        return executeAndRecordMetrics(
          indexer,
          gqlLogger,
          'getStateByCID',
          expressContext,
          async () => {
            const state = await indexer.getStateByCID(cid);

            return state && state.block.isComplete ? getResultState(state) : undefined;
          }
        );
      },

      getState: async (
        _: any,
        { blockHash, contractAddress, kind }: { blockHash: string, contractAddress: string, kind: string },
        expressContext: ExpressContext
      ) => {
        log('getState', blockHash, contractAddress, kind);

        return executeAndRecordMetrics(
          indexer,
          gqlLogger,
          'getState',
          expressContext,
          async () => {
            const state = await indexer.getPrevState(blockHash, contractAddress, kind);

            return state && state.block.isComplete ? getResultState(state) : undefined;
          }
        );
      },

      _meta: async (
        _: any,
        { block = {} }: { block: BlockHeight },
        expressContext: ExpressContext
      ) => {
        log('_meta');

        return executeAndRecordMetrics(
          indexer,
          gqlLogger,
          '_meta',
          expressContext,
          async () => indexer.getMetaData(block)
        );
      },

      getSyncStatus: async (
        _: any,
        __: Record<string, never>,
        expressContext: ExpressContext
      ) => {
        log('getSyncStatus');

        return executeAndRecordMetrics(
          indexer,
          gqlLogger,
          'getSyncStatus',
          expressContext,
          async () => indexer.getSyncStatus()
        );
      }
    }
  };
};
