// MyProject — Fastify Backend Server
import Fastify from "fastify";
import cors from "@fastify/cors";
import fjwt from "@fastify/jwt";
import { initDb, closeDb } from "./db/client.js";
import { authRoutes } from "./routes/auth.js";
import { contractsRoutes } from "./routes/contracts.js";
import { approvalsRoutes } from "./routes/approvals.js";
import { customersRoutes } from "./routes/customers.js";
import { remindersRoutes } from "./routes/reminders.js";
import { assetsRoutes } from "./routes/assets.js";
import { itemsRoutes } from "./routes/items.js";
import { statsRoutes } from "./routes/stats.js";

const JWT_SECRET = process.env.JWT_SECRET || "change-me-in-production-8dd37ee5";

export async function buildApp() {
  const app = Fastify({
    logger: {
      level: process.env.LOG_LEVEL || "info",
      transport: process.env.NODE_ENV !== "production"
        ? { target: "pino-pretty", options: { colorize: true } }
        : undefined,
    },
  });

  // Init database
  await initDb();

  // Plugins
  await app.register(cors, {
    origin: process.env.CORS_ORIGIN || "*",
    methods: ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
  });

  await app.register(fjwt, { secret: JWT_SECRET });

  // Routes
  await app.register(authRoutes, { prefix: "/api/auth" });
  await app.register(contractsRoutes, { prefix: "/api/contracts" });
  await app.register(approvalsRoutes, { prefix: "/api/approvals" });
  await app.register(customersRoutes, { prefix: "/api/customers" });
  await app.register(remindersRoutes, { prefix: "/api/reminders" });
  await app.register(assetsRoutes, { prefix: "/api/assets" });
  await app.register(itemsRoutes, { prefix: "/api/items" });
  await app.register(statsRoutes, { prefix: "/api/stats" });

  // Health check
  app.get("/api/health", async () => ({ status: "ok", timestamp: new Date().toISOString() }));

  // Graceful shutdown
  app.addHook("onClose", async () => {
    closeDb();
  });

  return app;
}

// Start server if called directly (not when imported by tests)
const port = parseInt(process.env.PORT || "3001", 10);
const host = process.env.HOST || "0.0.0.0";

async function main() {
  const app = await buildApp();
  try {
    await app.listen({ port, host });
  } catch (err) {
    app.log.error(err);
    process.exit(1);
  }
}

// Guard: only run when executed directly, not when imported
const isMain = process.argv[1] && (import.meta.url === `file://${process.argv[1]}` || import.meta.url.endsWith(process.argv[1]) || process.argv[1].endsWith("/src/index.ts") || process.argv[1].endsWith("/src/index.js"));
if (isMain) {
  main();
}
