import dotenv from 'dotenv'
dotenv.config()
import express from 'express'
import cookieParser from 'cookie-parser'
import { ApolloServer, ApolloServerExpressConfig } from 'apollo-server-express'
import { merge } from 'lodash'
import { importSchema } from 'graphql-import'
import { db, populateUser } from './src/db'
import { authenticate } from './src/user/authenticate'
//import file from './src/file'
import user from './src/user'
import history from './src/history'
//import google from './src/google'
import training from './src/training'

const resolvers = merge(
  //file.resolvers,
  training.resolvers,
  user.resolvers,
  history.resolvers
  //google.resolvers
)

const typeDefs = importSchema('./schema.graphql').replace('scalar Upload', '')
// scalar Upload has to be in schema, or importSchema will complain.
// But when it's in the schema, Apollo Server will still add it.
// Workaround: remove it manually here after the import.
// https://github.com/ardatan/graphql-import/issues/286

const corsOptions = {
  credentials: true,
  origin: process.env.FRONTEND_URL
}

const app = express()
app.use(cookieParser())
app.use(authenticate)
app.use(populateUser)

const server = new ApolloServer({
  typeDefs,
  resolvers,
  playground: true,
  context: (req: any) => ({
    ...req,
    db
  }),
  debug: false,
  engine: { debugPrintReports: false }
} as ApolloServerExpressConfig)
server.applyMiddleware({ app, cors: corsOptions })

app.listen({ port: process.env.PORT }, () => {
  console.log(
    `Server ready at http://localhost:${process.env.PORT}/${server.graphqlPath} 🚀!`
  )
})

export default app
