import express from 'express';
import session from 'express-session';
import Keycloak from 'keycloak-connect';
import cors from 'cors';
import {routeLogin } from './route-login';
import {routeProjects } from './route-projects';
import { routeGenerate } from './route-generate';
import http from 'http';
if (
    !process.env.KEYCLOAK_REALM_NAME
    || !process.env.KEYCLOAK_URL
    || !process.env.KEYCLOAK_CLIENT_ID
    || !process.env.KEYCLOAK_CLIENT_SECRET
) {
    throw new Error('Parametrs keycloak not setted')
}

const app = express();
const server = http.createServer(app);

server.requestTimeout = 10 * 60 * 1000;
server.headersTimeout = 10 * 60 * 1000;
// server.keepAliveTimeout = 10 * 60 * 1000;

app.use(cors({
  origin: "http://localhost:8080",
  credentials: true,
}));
// app.use(cors({
//   origin: '0.0.0.0:3000',
//   credentials: true,
//   methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
//   allowedHeaders: ["Content-Type", "Authorization"]
// }))
app.use(express.json());

const memoryStore = new session.MemoryStore();

app.use(
    session({
        secret: process.env.KEYCLOAK_CLIENT_SECRET,
        resave: false,
        saveUninitialized: false,
        store: memoryStore,
        cookie: {
            httpOnly: true,
            sameSite: 'lax',
            // secure: true, // включить https
            maxAge: 1000 * 60 * 60
        }
    })
)

const keycloak = new Keycloak(
    { store: memoryStore }, 
    {
        realm: process.env.KEYCLOAK_REALM_NAME,
        "auth-server-url": process.env.KEYCLOAK_URL,
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        //@ts-ignore 
        "client-id": process.env.KEYCLOAK_CLIENT_ID,
        "bearer-only": true,
        "ssl-required": "external",
        resource: process.env.KEYCLOAK_CLIENT_ID,
        credentials: {secret: process.env.KEYCLOAK_CLIENT_SECRET},
        "confidential-port": 0,
    }
);

routeLogin(app, keycloak);
routeProjects(app);
routeGenerate(app);

// app.get('/me', keycloak.protect(), (req, res) => {
//   const grant = req.kauth?.grant;
//   const tokenContent = grant?.access_token?.content || {};
//   res.json({
//     sub: tokenContent.sub,
//     preferred_username: tokenContent.preferred_username,
//     email: tokenContent.email,
//     roles: tokenContent.realm_access?.roles || [],
//   });
// });

app.post('/logout', (req, res) => {
  try {
    req.session.destroy(() => {
      res.status(204).end();
    });
  } catch {
    res.status(204).end();
  }
});


app.get('/healthz', (_req, res) => res.send('ok'));

const port = String(process.env.PORT || 3000);
server.listen(port, () => {
  console.log(`Auth server listening on http://localhost:${port}`);
});
