import { ApolloServer } from 'apollo-server';
import { PrismaClient } from '@prisma/client';
import * as fs from 'fs';  
import * as path from 'path';  
import jwt from 'jsonwebtoken';
import { queryResolvers } from './resolvers/queryResolvers.ts';  // Import query resolvers
import { mutationResolvers } from './resolvers/mutationResolvers.ts';  // Import mutation resolvers

// Get __dirname equivalent in ES Modules
const __dirname = path.dirname(new URL(import.meta.url).pathname);

// Load schema.graphql
const typeDefs = fs.readFileSync(path.join(__dirname, 'schema.graphql'), 'utf8');

// Initialize Prisma
const prisma = new PrismaClient();

const JWT_SECRET = 'your-jwt-secret'; // You should store this in environment variables

// Generate JWT token
export function generateToken(user) {
  return jwt.sign({ userId: user.id }, JWT_SECRET, { expiresIn: '1h' });
}

// Middleware to authenticate users
const getUserFromToken = (token) => {
  try {
    return jwt.verify(token, JWT_SECRET);
  } catch (error) {
    return null;
  }
};

// GraphQL Resolvers
const resolvers = {
  Query: queryResolvers,
  Mutation: mutationResolvers,
};

// Initialize Apollo Server
const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: ({ req }) => {
    const token = req.headers.authorization || '';
    const user = token ? getUserFromToken(token.replace('Bearer ', '')) : null;
    return {
      prisma,
      user,
    };
  },
});

// Start the server
server.listen().then(({ url }) => {
  console.log(`🚀 Server is running at ${url}`);
});
