import express from 'express';
import session from 'express-session';
import Keycloak from 'keycloak-connect';
import cors from 'cors';
import { books } from './books.js';

const app = express();
app.use(cors());

const memoryStore = new session.MemoryStore();

app.use(
  session({
    secret: 'some-secret',
    resave: false,
    saveUninitialized: true,
    store: memoryStore,
  }),
);

const keycloak = new Keycloak(
  { store: memoryStore },
  {
    realm: 'demo',
    'auth-server-url': 'http://localhost:8080',
    'ssl-required': 'none',
    resource: 'express-api',
    credentials: {
      secret: 'express-secret',
    },
    'confidential-port': 0,
  },
);

app.use(keycloak.middleware());

app.get('/books', keycloak.protect('realm:reader'), (req, res) => {
  res.json(books);
});

app.listen(3001, () => console.log('API running on http://localhost:3001'));
