let passport = require('passport');
let express = require('express');
let https = require('https');
let fs = require('fs');

let app = express();
require('./config/passport.js');

let session = require('express-session');

app.use(session({
  secret: 'RLCCDwstDuT6nMJf5kko7C',
  resave: false,
  saveUninitialized: true
}));

// ... rest of your code ...

app.use(passport.initialize());
app.use(passport.session());

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

app.get('/', function (req, res) {
  response = 'Hello World!<br>';
  console.log('User:', req.user);
  if (req.user) {
    console.log('User:', req.user);
    response += 'Username: ' + req.user.username + '<br>';
    response += 'First Name: ' + req.user.first_name + '<br>';
    response += 'Last Name: ' + req.user.last_name + '<br>';
    response += 'Org Unit: ' + req.user.org_unit + '<br>';
    response += '<a href="/logout">Logout</a>';
  }
  else {
    response += '<a href="/login">Login</a>';
  }
  res.send(response);
});

app.get('/logout', function (req, res) {
  req.logout();
  res.redirect('/');
});

app.get('/login',
  passport.authenticate('saml', { failureRedirect: '/selfservice', failureFlash: true }),
  function (req, res) {
    res.redirect('https://localhost:3000/');
  }
);

app.use(function(req, res, next) {
  console.log('Received request:', req.method, req.url);
  console.log('Data:', req.body);
  next();
});

app.post('/selfservice/activedirectory/postResponse',
  passport.authenticate('saml', { failureRedirect: '/selfservice',successRedirect: '/', failureFlash: true }),
  function (req, res) {
    console.log('SAML authentication successful');
    res.redirect('https://localhost:3000/');
  }
);
//app.get('selfservice/secure', validUser, routes.secure);

function validUser(req, res, next) {
  if (!req.user) {
    res.redirect('https://localhost:3000/login');
  }
  next();
}

const options = {
  key: fs.readFileSync('adfs_connect/urn_satitm_sso_selfservice.key'),
  cert: fs.readFileSync('adfs_connect/urn_satitm_sso_selfservice.cert'),
  ciphers: [
    'ECDHE-RSA-AES128-GCM-SHA256',
    'ECDHE-ECDSA-AES128-GCM-SHA256',
    'ECDHE-RSA-AES256-GCM-SHA384',
    'ECDHE-ECDSA-AES256-GCM-SHA384',
    'DHE-RSA-AES128-GCM-SHA256',
    'ECDHE-RSA-AES128-SHA256',
    'DHE-RSA-AES128-SHA256',
    'ECDHE-RSA-AES256-SHA384',
    'DHE-RSA-AES256-SHA384',
    'ECDHE-RSA-AES256-SHA256',
    'DHE-RSA-AES256-SHA256',
    'HIGH',
    '!aNULL',
    '!eNULL',
    '!EXPORT',
    '!DES',
    '!RC4',
    '!MD5',
    '!PSK',
    '!SRP',
    '!CAMELLIA'
  ].join(':'),
  honorCipherOrder: true
};

let server = https.createServer(options, app);
server.listen(3000, function () {
  console.log('Listening on port 3000');
});