const express = require('express');
const { ApolloServer } = require('apollo-server-express');
const path = require('path');
const db = require('./config/connection');
const typeDefs = require('./schemas/typeDefs');
const resolvers = require('./schemas/resolvers');
const { authMiddleware } = require('./utils/auth');

const PORT = process.env.PORT || 3001;
const app = express();

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

// Apply your authentication middleware globally for all routes
app.use(authMiddleware);

const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: ({ req }) => {
    // Make sure to include the req object in the context
    return { req };
  },
});

// Start the Apollo Server and apply middleware
server.start().then(() => {
  server.applyMiddleware({ app, path: '/graphql' });

  // Serve static assets if in production
  if (process.env.NODE_ENV === 'production') {
    app.use(express.static(path.join(__dirname, '../client/dist')));
    app.get('*', (req, res) => {
      res.sendFile(path.join(__dirname, '../client/dist/index.html'));
    });
  }

  // Start the Express server
  app.listen(PORT, () => {
    console.log(`🌍 Now listening on localhost:${PORT}`);
    console.log(`🚀 Apollo Server ready at http://localhost:${PORT}${server.graphqlPath}`);
  });
});

// Set up the database connection
db.once('open', () => {
  console.log('Connected to the database');
});

// Handle any database connection errors
db.on('error', (error) => {
  console.error('Database connection error:', error);
});