import type { Request, Response, NextFunction } from "express";
import { eq } from "drizzle-orm";
import { db } from "@workspace/db";
import { systemSettingsTable } from "@workspace/db";

// Gate /api/setup/{validate,complete} on system_settings.installed
// (the single source of truth). The admin-existence cross-check
// lives inside the POST /setup/complete transaction.
// /api/setup/status is intentionally NOT guarded.
export async function requireSetupOpen(
  _req: Request,
  res: Response,
  next: NextFunction,
): Promise<void> {
  try {
    const rows = await db
      .select({ installed: systemSettingsTable.installed })
      .from(systemSettingsTable)
      .where(eq(systemSettingsTable.id, 1))
      .limit(1);
    const installed = rows[0]?.installed ?? false;
    if (installed) {
      res.status(409).json({
        error: "already_installed",
        message: "Setup has already been completed.",
      });
      return;
    }
    next();
  } catch (err) {
    next(err as Error);
  }
}
