import { Router, type IRouter } from "express";
import { setupRateLimit, setupStatusRateLimit } from "../lib/setupRateLimit";
import { requireSetupOpen } from "../middlewares/setupGate";
import {
  readStatus,
  validateProposed,
  completeInstall,
} from "../lib/setupService";
import { logger } from "../lib/logger";

const router: IRouter = Router();

// Status is read-only and must remain reachable AFTER install too, so the
// SPA can decide routing. It is rate-limited but NOT gated.
router.get("/setup/status", setupStatusRateLimit, async (_req, res, next) => {
  try {
    const status = await readStatus();
    res.json(status);
  } catch (err) {
    next(err as Error);
  }
});

router.post(
  "/setup/validate",
  setupRateLimit,
  requireSetupOpen,
  async (req, res, next) => {
    try {
      const result = await validateProposed(req.body);
      if (result.ok) {
        res.json({ ok: true });
      } else {
        res.status(400).json({ ok: false, errors: result.errors });
      }
    } catch (err) {
      next(err as Error);
    }
  },
);

router.post(
  "/setup/complete",
  setupRateLimit,
  requireSetupOpen,
  async (req, res, next) => {
    try {
      const result = await completeInstall(req.body);
      if (result.ok) {
        logger.info(
          { userId: result.userId },
          "[setup] first-time install completed",
        );
        res.json({ ok: true });
      } else {
        res
          .status(result.status)
          .json({ ok: false, error: result.error, errors: result.errors });
      }
    } catch (err) {
      next(err as Error);
    }
  },
);

export default router;
