import { Hono } from "hono";
import { z } from "zod";
import { validateToken, isNoAuthMode } from "../auth-middleware.js";
import { extractBearerToken } from "../auth-middleware.js";
import { parseBody } from "../validation.js";

// ─── Zod Schemas ──────────────────────────────────────────────────

const authValidateSchema = z.object({
  token: z.string(),
});

/**
 * Creates unauthenticated auth routes for the login flow.
 * These must be mounted BEFORE the auth middleware so they are accessible
 * without a token.
 */
export function createAuthRoutes(): Hono {
  const app = new Hono();

  /**
   * GET /auth/check
   *
   * Returns the current auth status. Used by the frontend to determine
   * whether a login page should be shown.
   *
   * - If the request already has a valid token: `{ authenticated: true }`
   * - If auth is disabled (--no-auth): `{ authenticated: true, noAuth: true }`
   * - Otherwise: `{ authenticated: false }`
   */
  app.get("/auth/check", (c) => {
    if (isNoAuthMode()) {
      return c.json({ authenticated: true, noAuth: true });
    }

    const authHeader = c.req.header("Authorization");
    const token = extractBearerToken(authHeader);
    if (token && validateToken(token)) {
      return c.json({ authenticated: true });
    }

    return c.json({ authenticated: false });
  });

  /**
   * POST /auth/validate
   *
   * Validates a token without using it for a protected operation.
   * The frontend calls this when the user enters a token on the login page.
   *
   * Body: `{ token: string }`
   * Response: `{ valid: boolean }`
   */
  app.post("/auth/validate", async (c) => {
    if (isNoAuthMode()) {
      return c.json({ valid: true });
    }

    const parsed = await parseBody(c, authValidateSchema);
    if (!parsed.success) return parsed.response;
    const token = parsed.data.token.trim();

    if (!token) {
      return c.json({ valid: false });
    }

    return c.json({ valid: validateToken(token) });
  });

  return app;
}
