import fp from 'fastify-plugin'
import fastifyEnv from '@fastify/env'

declare module 'fastify' {
  export interface FastifyInstance {
    config: {
      PORT: number;
      COOKIE_SECRET: string;
      COOKIE_NAME: string;
      COOKIE_SECURED: boolean;
      RATE_LIMIT_MAX: number;
      PRIVY_APP_ID: string;
      PRIVY_APP_SECRET: string;
      PRIVY_AUTHORIZATION_KEY: string;
      SENTRY_DSN: string;
      SENTRY_ENVIRONMENT: string;
      GMX_UI_FEE_RECEIVER: string;
    };
  }
}

const schema = {
  type: 'object',
  required: [
    'PORT',
    'COOKIE_SECRET',
    'COOKIE_NAME'
  ],
  properties: {
    PORT: {
      type: 'number',
      default: 4111
    },
    COOKIE_SECRET: {
      type: 'string'
    },
    COOKIE_NAME: {
      type: 'string',
      default: 'web3proxy'
    },
    COOKIE_SECURED: {
      type: 'boolean',
      default: true
    },
    RATE_LIMIT_MAX: {
      type: 'number',
      default: 100
    },
    SENTRY_DSN: {
      type: 'string'
    },
    SENTRY_ENVIRONMENT: {
      type: 'string',
      default: 'development'
    },
    GMX_UI_FEE_RECEIVER: {
      type: 'string',
    }
  }
}

export const autoConfig = {
  // Decorate Fastify instance with `config` key
  // Optional, default: 'config'
  confKey: 'config',

  // Schema to validate
  schema,

  // Needed to read .env in root folder
  dotenv: true,
  // or, pass config options available on dotenv module
  // dotenv: {
  //   path: `${import.meta.dirname}/.env`,
  //   debug: true
  // }

  // Source for the configuration data
  // Optional, default: process.env
  data: process.env
}

/**
 * This plugins helps to check environment variables.
 *
 * @see {@link https://github.com/fastify/fastify-env}
 */
export default fp(async (fastify) => {
  const schema = {
    type: 'object',
    required: ['PRIVY_APP_ID', 'PRIVY_APP_SECRET', 'PRIVY_AUTHORIZATION_KEY', 'COOKIE_SECRET'],
    properties: {
      PRIVY_APP_ID: {
        type: 'string'
      },
      PRIVY_APP_SECRET: {
        type: 'string'
      },
      PRIVY_AUTHORIZATION_KEY: {
        type: 'string'
      },
      COOKIE_SECRET: {
        type: 'string'
      },
      COOKIE_NAME: {
        type: 'string',
        default: 'web3proxy'
      },
      COOKIE_SECURED: {
        type: 'boolean',
        default: false
      },
      SENTRY_DSN: {
        type: 'string'
      },
      SENTRY_ENVIRONMENT: {
        type: 'string'
      },
      GMX_UI_FEE_RECEIVER: {
        type: 'string',
      }
    }
  }

  const options = {
    confKey: 'config',
    schema: schema,
    dotenv: true,
    data: process.env
  }

  await fastify.register(fastifyEnv, options)
}, {
  name: 'env-config'
})
