import type { FastifyInstance } from "fastify";
import { z } from "zod";
import { parse, route } from "../../core/http/route.js";
import { demoAccounts, demoLogin } from "./demo.service.js";
import * as s from "./identity.service.js";

const str = z.string().min(1).max(300);
export async function identityRoutes(app: FastifyInstance): Promise<void> {
  route(app, "POST", "/auth/login", { public: true, limit: 20, v1: ["POST /api/auth/login"] }, async (c) => { const b = parse(z.object({ email: str, password: str, remember: z.boolean().default(false) }), c.body); return s.login(c, b.email, b.password, b.remember); });
  route(app, "POST", "/auth/2fa/verify", { public: true, limit: 20, v1: ["POST /api/auth/verify-2fa"] }, async (c) => { const b = parse(z.object({ challengeId: str, code: str }), c.body); return s.verify2fa(c, b.challengeId, b.code); });
  route(app, "POST", "/auth/2fa/resend", { public: true, limit: 5, v1: ["POST /api/auth/resend-2fa"] }, async (c) => s.resend2fa(parse(z.object({ challengeId: str }), c.body).challengeId));
  route(app, "GET", "/auth/demo", { public: true }, async (c) => demoAccounts(c));
  route(app, "POST", "/auth/demo/:id", { public: true, limit: 60 }, async (c) => demoLogin(c, c.params["id"]!));
  route(app, "POST", "/auth/logout", { public: true, v1: ["POST /api/auth/logout"] }, async (c) => s.logout(c));
  route(app, "GET", "/auth/me", { allowPasswordChange: true, v1: ["GET /api/auth/me"] }, async (c) => s.me(c));
  route(app, "POST", "/auth/password/forgot", { public: true, limit: 5 }, async (c) => s.forgotPassword(parse(z.object({ email: str }), c.body).email));
  route(app, "POST", "/auth/password/reset", { public: true, limit: 10, v1: ["POST /api/auth/reset-password"] }, async (c) => { const b = parse(z.object({ token: str, new: str }), c.body); return s.resetPassword(b.token, b.new); });
  route(app, "POST", "/auth/password/change", { allowPasswordChange: true, limit: 10, v1: ["POST /api/auth/change-password", "POST /api/auth/change-password-required"] }, async (c) => { const b = parse(z.object({ current: str, new: str }), c.body); return s.changePassword(c, b.current, b.new); });
  route(app, "GET", "/auth/invites", { public: true, limit: 20 }, async (c) => s.getInvite(c.query["token"] ?? ""));
  route(app, "POST", "/auth/invites/accept", { public: true, limit: 10 }, async (c) => { const b = parse(z.object({ token: str, name: str, password: str }), c.body); return s.acceptInvite(c, b.token, b.name, b.password); });
  route(app, "GET", "/auth/sessions", {}, async (c) => s.listSessions(c));
  route(app, "POST", "/auth/sessions/:id/revoke", {}, async (c) => s.revokeSession(c, c.params["id"]!));
  route(app, "POST", "/auth/2fa/totp/setup", {}, async (c) => s.setupTotp(c));
  route(app, "POST", "/auth/2fa/totp/confirm", { limit: 10 }, async (c) => s.confirmTotp(c, parse(z.object({ code: str }), c.body).code));
}
