import express from "express";
import cors from "cors";
import helmet from "helmet";
import morgan from "morgan";
import cookieParser from "cookie-parser";
import fs from "fs";
import path from "path";

import { connectDb } from "./shared/db.js";
import { env } from "./shared/env.js";
import { notFound, errorHandler } from "./shared/errors.js";
import { apiRouter } from "./routes.js";

const app = express();

app.use(helmet());
app.use(
  cors({
    origin: (origin, cb) => {
      // Allow native apps (no Origin header) and allow-list for web.
      if (!origin) return cb(null, true);
      const allowList = String(env.CORS_ORIGIN || "")
        .split(",")
        .map((s) => s.trim())
        .filter(Boolean);

      if (allowList.length === 0) return cb(null, true);
      if (allowList.includes("*")) return cb(null, true);
      if (allowList.includes(origin)) return cb(null, true);
      return cb(new Error(`CORS blocked for origin: ${origin}`));
    },
    credentials: true,
  })
);
app.use(cookieParser());
app.use(express.json({ limit: "1mb" }));
app.use(morgan(env.NODE_ENV === "production" ? "combined" : "dev"));

// Serve uploaded files (chat attachments)
const uploadsDir = path.join(process.cwd(), "uploads");
fs.mkdirSync(uploadsDir, { recursive: true });
app.use("/uploads", express.static(uploadsDir));

app.get("/health", (_req, res) => {
  res.json({
    ok: true,
    service: "Somarjun Tech company - Office Management API",
    time: new Date().toISOString(),
  });
});

app.get("/", (_req, res) => {
  res.json({
    ok: true,
    message: "Somarjun Tech company - Office Management API",
  });
});

app.use("/api", apiRouter);

app.use(notFound);
app.use(errorHandler);

await connectDb();

app.listen(env.PORT, "0.0.0.0", () => {
  // eslint-disable-next-line no-console
  console.log(`API listening on http://localhost:${env.PORT}`);
  console.log(
    `Also accessible via http://0.0.0.0:${env.PORT} (for Android emu/devices)`
  );
});
