# data[].attributes.attachment_link.readable_text
const express = require('express');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');

const app = express();

const fixedsalt = '$2b$10$J9p8h1TEhTN6hjkf0p6f2O';

// Middleware to parse JSON body
app.use(express.json());

// Mock User Model
const users = [];

bcrypt.hash("karimi@523", fixedsalt)
  .then(hashedPassword => {
    // Create user object with hashed password
    const user = {
      id: 1,
      name: 'karimi',
      email: 'karimi@example.com',
      password: hashedPassword
    };

    // Add user to users array
    users.push(user);

    // Start the server after the user has been created
    app.listen(3004, () => {
      console.log('Server started on port 3004');
    });
  })
  .catch(error => {
    console.error('Error hashing password:', error);
  });

// Login Route
app.post('/login', (req, res) => {
  const { email, password } = req.body;

  // Find user by email
  const user = users.find(user => user.email == email);
  if (!user) {
    return res.status(401).json({ error: 'User not found!' });
  }

  // Compare password using bcrypt
  bcrypt.compare(password, user.password)
    .then(isMatch => {
      if (!isMatch) {
        return res.status(401).json({ error: 'Incorrect password!' });
      }
      
      // Generate JWT token
      const token = jwt.sign({ userId: user.id }, 'SECRET_KEY', { expiresIn: '1h' });

      res.status(200).json({ token });
    })
    .catch(error => res.status(500).json({ error }));
});

# data[].attributes.attachment_link.readable_text
//ref to CRUD operations on MongoDB(insertone(), ...) => https://www.mongodb.com/docs/manual/reference/method/

const express = require('express');
const { MongoClient } = require('mongodb');

const app = express();
const port = 3000; // Set the desired port number


app.get('/stagiaires', async (req, res) => {
    try {
        const client = new MongoClient('mongodb://127.0.0.1:27017', { useNewUrlParser: true, useUnifiedTopology: true });
        await client.connect();
    
        const db = client.db('formation'); // Replace with your database name
        const collection = db.collection('stagiaire'); // Replace with your collection name

      const result = await collection.find({}).toArray(); // Retrieve all documents
  
      res.json(result); // Send the retrieved data as JSON response
  
      client.close();
    } catch (error) {
      console.error('Error retrieving data:', error);
      res.status(500).send('Error retrieving data', error);
    }
  });

  /*
    The json() middleware in the app.post() method of Express.js is responsible for parsing 
    the incoming request body in JSON format. 
    It is used to extract the JSON data sent in the request and make it accessible in the req.body 
    property for further processing in the route handler.
  */
  app.post('/stagiaires', express.json(), async (req, res) => {
    try {
        const client = new MongoClient('mongodb://127.0.0.1:27017', { useNewUrlParser: true, useUnifiedTopology: true });
        await client.connect();
    
        const db = client.db('formation'); // Replace with your database name
        const collection = db.collection('stagiaire'); // Replace with your collection name

      const document = req.body; // Assuming the request body contains the data to be inserted
  
      const result = await collection.insertOne(document);
  
      res.send('stagiaire inserted successfuly');
  
      client.close();
    } catch (error) {
      console.error('Error creating data:', error);
      res.status(500).send('Error creating data');
    }
  });

  app.delete('/stagiaires/:cne', async (req, res) => {
    try {
        const client = new MongoClient('mongodb://127.0.0.1:27017', { useNewUrlParser: true, useUnifiedTopology: true });
        await client.connect();
    
        const db = client.db('formation'); 
        const collection = db.collection('stagiaire');

      const cneparam = req.params.cne; // Assuming the request body contains the data to be inserted
      //res.send("typeof req.body.cne " + typeof req.params.cne);
      const result = await collection.deleteOne({ cne : parseInt(cneparam) });
      res.send(`${result.deletedCount} stagiaire deleted successfuly`);  
      client.close();
    } catch (error) {
      console.error('Error deleting data:', error);
      res.status(500).send('Error deleting data' + error);
    }
  });

  app.put('/stagiaires/:cne', express.json(), async (req, res) => {
    try {
        const client = new MongoClient('mongodb://127.0.0.1:27017', { useNewUrlParser: true, useUnifiedTopology: true });
        await client.connect();
    
        const db = client.db('formation'); // Replace with your database name
        const collection = db.collection('stagiaire'); // Replace with your collection name

      const document = req.body; // Assuming the request body contains the data to be inserted
      const cneparam = req.params.cne;
  
      const result = await collection.updateOne({cne: parseInt(cneparam) }, {$set:document});
  
      res.send(`${result.modifiedCount} stagiaire updated successfuly`);
  
      client.close();
    } catch (error) {
      console.error('Error updating data:', error);
      res.status(500).send('Error updating data' + error);
    }
  });
  
  app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
  });
  
  