import Koa from "koa";
import bodyParser from "koa-bodyparser";
import router from "./routes";
import { authenticate, handleJwtError } from "./middleware/auth";
import DatabaseService from "./services/database";
import cors from "@koa/cors";

const app = new Koa();
const PORT = process.env.PORT || 3000;
const db = DatabaseService.getInstance();

// Connect to database
db.connect()
  .then(() => {
    console.log("Database connection established");
  })
  .catch((err) => {
    console.error("Database connection failed:", err);
    process.exit(1);
  });

// Middlewares
app.use(
  cors({
    origin: "*",
    allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    allowHeaders: ["Content-Type", "Authorization", "Accept"],
    credentials: true,
    exposeHeaders: ["WWW-Authenticate", "Server-Authorization"],
    maxAge: 86400, // 1 day
  }),
);
app.use(bodyParser());
app.use(handleJwtError);
app.use(authenticate);
app.use(router.routes());
app.use(router.allowedMethods());

// Error handling
app.on("error", (err, ctx) => {
  console.error("Server error:", err);
  ctx.status = err.status || 500;
  ctx.body = {
    success: false,
    message: err.message || "Internal server error",
  };
});

// Start server
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});

// Handle graceful shutdown
process.on("SIGINT", async () => {
  console.log("Shutting down server...");
  try {
    await db.disconnect();
    process.exit(0);
  } catch (error) {
    console.error("Error during shutdown:", error);
    process.exit(1);
  }
});

export default app;
