import type { FastifyInstance } from "fastify";
import { z } from "zod";
import { syncAccount, syncAllActive } from "../../sync/index.js";
import { listSpot } from "../../repos/spot.js";
import { writeAudit } from "../../audit/audit.js";

/** Rotas de sync manual + leitura do cache de spot. Nível operador. */

const idParams = z.object({ id: z.coerce.number().int().positive() });

export async function syncRoutes(app: FastifyInstance): Promise<void> {
  const auth = { preHandler: app.authenticate };

  app.post("/sync", auth, async (req) => {
    const results = await syncAllActive();
    await writeAudit({ userId: req.user.sub, action: "sync.all", entity: "sync" });
    return results;
  });

  app.post("/accounts/:id/sync", auth, async (req) => {
    const { id } = idParams.parse(req.params);
    const result = await syncAccount(id);
    await writeAudit({ userId: req.user.sub, action: "sync.account", entity: "exchange_account", entityId: id });
    return result;
  });

  app.get("/spot", auth, async () => listSpot());
}
