"use strict";

require("dotenv").config();

process.on("uncaughtException", (error) => {
  console.error("Uncaught Exception:", error);
  if (error.stack) console.error(error.stack);
  setTimeout(() => {
    process.exit(1);
  }, 1000);
});

process.on("unhandledRejection", (reason, promise) => {
  console.error("Unhandled Rejection at:", promise);
  console.error("Reason:", reason);
  if (process.env.NODE_ENV !== "production") {
    setTimeout(() => {
      process.exit(1);
    }, 1000);
  }
});

const Application = require("./src/app");

const PORT = Number(process.env.PORT) || 3000;

function logStartup() {
  console.log(`Keez invoice API listening on http://localhost:${PORT}`);
  console.log(`POST http://localhost:${PORT}/invoices`);
  console.log(
    `Item resolution: default on (script.py flow). KEEZ_AUTO_CREATE_ITEM=${process.env.KEEZ_AUTO_CREATE_ITEM !== "false"}`
  );
  const hasSecret = Boolean((process.env.API_SECRET || "").trim());
  if (hasSecret) {
    console.log("API_SECRET: setat — POST /invoices necesită Bearer sau X-API-Key.");
  } else {
    console.warn(
      "[keez-api] API_SECRET lipsește — POST /invoices este public. Setează API_SECRET în producție."
    );
  }
}

function startServer() {
  Application.server.listen(PORT, logStartup);

  Application.server.on("error", (error) => {
    if (error.code === "EADDRINUSE") {
      console.error(`Port ${PORT} is already in use. Cannot start server.`);
    } else {
      console.error("Server error:", error);
    }
    setTimeout(() => {
      process.exit(1);
    }, 1000);
  });

  function shutdown(signal) {
    console.log(`${signal} received, closing server gracefully...`);
    Application.server.close(() => {
      console.log("Server closed");
      process.exit(0);
    });
  }

  process.on("SIGTERM", () => shutdown("SIGTERM"));
  process.on("SIGINT", () => shutdown("SIGINT"));
}

if (require.main === module) {
  startServer();
}

/** Passenger (cPanel): folosește aplicația Express, nu http.Server. */
module.exports = Application.app;
