import fs from 'fs';
import swaggerJsdoc from "swagger-jsdoc";
import swaggerUi from "swagger-ui-express";
import https from 'https';
import express from 'express';
import cors from 'cors';
import path from 'path';
import apiRouter, { ApiError, generateRequestBodies } from './api.js';
import { initDB } from './db.js';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.join(path.dirname(__filename), ".."); // going back a dir cuz code is in src/

const app = express();

const specs = swaggerJsdoc({
  definition: {
    openapi: "3.0.0",
    info: {
      title: "Analogue Game Assistent API",
      version: "1.0.0",
    }
  },
  apis: ["./src/api.js"],
});
for (const [path, schema] of Object.entries(generateRequestBodies())) {
  const swaggerPath = path.replace(/:(\w+)/g, '{$1}');
  if (!specs.paths[swaggerPath]) continue;

  const methodKeys = Object.keys(specs.paths[swaggerPath]);
  methodKeys.forEach(method => {
    if (["post", "put", "patch", "delete"].includes(method)) {
      specs.paths[swaggerPath][method].requestBody = schema;
    }
  });
}

initDB();

app.use(cors());
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(express.static(path.join(__dirname, "public"), {
  dotfiles: "ignore"
}));
app.use("/api/docs", swaggerUi.serve, swaggerUi.setup(specs));
app.use("/api", apiRouter);

app.use((err, req, res, next) => {
  if (err instanceof ApiError) {
    if (err.cause != null) {
      console.error(err.cause);
    }
    return res.status(err.status).json({ status: "error", error: err.message });
  }

  console.error(err);
  res.status(500).json({ status: "error", error: "Internal server error" });
});

const server = https.createServer({
  key: fs.readFileSync('server.key'),
  cert: fs.readFileSync('server.cert')
}, app).listen(5555, () => {
  console.log(`Server running on http://localhost:${server.address().port}`);
});