import { env } from "../config/env.js";
import { runPricingOnce } from "../pricing/worker.js";
import { syncAdsForAccount } from "../sync/index.js";
import { list as listAccounts } from "../accounts/repository.js";
import { ping as pingDb, closePool } from "../db/mysql.js";

/**
 * Processo do worker de PRICING (sempre-vivo). A cada ciclo: espelha os
 * anúncios das contas ativas e roda um ciclo de pricing (dry-run por padrão).
 */

let running = true;

function sleep(ms: number): Promise<void> {
  return new Promise((r) => setTimeout(r, ms));
}

async function cycle(): Promise<void> {
  const accounts = (await listAccounts()).filter((a) => a.active);
  for (const acc of accounts) {
    try {
      await syncAdsForAccount(acc.id);
    } catch (err) {
      console.error(`[pricing] sync ads conta ${acc.id} falhou:`, errMsg(err));
    }
  }

  const results = await runPricingOnce();
  const applied = results.filter((r) => r.applied).length;
  console.log(
    `[pricing] ${results.length} anúncio(s), ${applied} aplicado(s) (PRICING_APPLY=${env.PRICING_APPLY ? "on" : "DRY-RUN"})`,
  );
  for (const r of results) {
    if (r.error) console.error(`[pricing] ad ${r.adId} (${r.advNo}): ${r.error}`);
    else if (r.warnings.length) console.warn(`[pricing] ad ${r.adId}: ${r.warnings.join("; ")}`);
  }
}

async function main(): Promise<void> {
  await pingDb();
  console.log(`[pricing] worker iniciado. Intervalo=${env.PRICING_INTERVAL_MS}ms, apply=${env.PRICING_APPLY}`);
  while (running) {
    try {
      await cycle();
    } catch (err) {
      console.error("[pricing] ciclo falhou:", errMsg(err));
    }
    await sleep(env.PRICING_INTERVAL_MS);
  }
}

function errMsg(err: unknown): string {
  return err instanceof Error ? err.message : String(err);
}

const shutdown = async (signal: string): Promise<void> => {
  console.log(`[pricing] ${signal} recebido, encerrando...`);
  running = false;
  await closePool().catch(() => {});
  process.exit(0);
};
process.on("SIGINT", () => void shutdown("SIGINT"));
process.on("SIGTERM", () => void shutdown("SIGTERM"));

main().catch((err) => {
  console.error("[pricing] fatal:", errMsg(err));
  process.exit(1);
});
