import { Module } from '@nestjs/common';
import { GraphQLModule} from '@nestjs/graphql';
import { ConnectionContext } from 'subscriptions-transport-ws';
import * as WebSocket from 'ws';

import { Client } from './client';
import { UUID } from './global/scalars/UUID';

import { GlobalModule } from './global/global.module';
import { PersonModule } from './person/person.module';
import { ApparatusModule } from './apparatus/apparatus.module';
import { OrganizerModule } from './organizer/organizer.module'
import { EventModule } from './event/event.module'

@Module({
  imports: [
    GlobalModule,
    PersonModule,
    ApparatusModule,
    OrganizerModule,
    EventModule,
    GraphQLModule.forRoot({
      installSubscriptionHandlers: true,
      autoSchemaFile: 'schema.gql',
      debug: false,
      playground: true,
      // path: 'gql',
      context: async ({ req, connection }) => {
        if (connection?.context?.client) {
          return { client: connection.context.client };
        }

        const client = new Client();

        if (req?.headers?.token) {
          await client.login({token: req.headers.token});
        }

        return { client }
      },
      subscriptions: {
        onConnect: (headers: { token: string, clientId: UUID }, websocket: any) => {
          const ip = websocket?.upgradeReq?.headers?.['x-forwarded-for'] || websocket._socket.remoteAddress;
          const client = new Client(headers.clientId, ip);

          if (headers.token) {
            client.login({token: headers.token}).then();
          }

          return { ...headers, client };
        },
        onDisconnect: (websocket: WebSocket, context: ConnectionContext) => {
          context.initPromise.then(() => {
          })
        },
      },
      resolvers: {},
    })
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}
