import type { FastifyInstance } from "fastify";
import { runPricingOnce } from "../../pricing/worker.js";
import { listAdjustments } from "../../repos/pricing.js";
import { writeAudit } from "../../audit/audit.js";

/**
 * Rotas de pricing. O "run" manual é sempre DRY-RUN (não aplica) — serve
 * para conferir os cálculos. A aplicação real fica a cargo do worker quando
 * PRICING_APPLY estiver ligado.
 */
export async function pricingRoutes(app: FastifyInstance): Promise<void> {
  const auth = { preHandler: app.authenticate };

  app.post("/pricing/run", auth, async (req) => {
    const results = await runPricingOnce(false); // força dry-run
    await writeAudit({
      userId: req.user.sub,
      action: "pricing.dry_run",
      entity: "pricing",
      detail: { count: results.length },
    });
    return { dryRun: true, results };
  });

  app.get("/pricing/adjustments", auth, async () => {
    return listAdjustments(undefined, 200);
  });
}
