import { pool, query } from "../../core/db/db.js";
import { readTable, toXlsx } from "../../core/files/table.js";
import { DomainError } from "../../core/http/errors.js";
import type { Ctx } from "../../core/http/route.js";
import { parseFormDate, today } from "../../shared/dates.js";
import { definitions, setTarget } from "./indicators.service.js";
import { resolveTargets } from "./kpi.service.js";

const HEAD = ["indicator_code", "indicator", "provider_code", "target", "effective_from", "note"];
const providersOf = (c: Ctx) => query(pool, "SELECT id, code FROM providers WHERE project_id=? ORDER BY code", [c.pid]);
/** One row per provider and indicator with today's target. Rows that are deleted or left unchanged change nothing. */
export async function template(c: Ctx): Promise<Buffer> {
  const defs = await definitions(c.pid), now = await resolveTargets(pool, c.pid, today()), rows = [];
  for (const p of await providersOf(c)) for (const d of defs) { const own = now.filter((t) => t["code"] === d["code"] && t["providerId"] !== null && String(t["providerId"]) === String(p["id"])).at(-1); rows.push([d["code"], d["name"], p["code"], own ? Number(own["value"]) : null, null, null] as (string | number | null)[]); }
  return toXlsx("Targets", HEAD, rows, ["effective_from"]);
}
/** Everything is checked first. If one row is wrong, nothing is saved. */
export async function importTargets(c: Ctx, name: string, data: Buffer) {
  const { header, rows } = await readTable(name, data), missing = ["indicator_code", "provider_code", "target"].filter((h) => !header.includes(h));
  if (missing.length) throw new DomainError(422, "VALIDATION", `The file has no column ${missing.join(", ")}.`);
  const defs = new Map((await definitions(c.pid)).map((d) => [String(d["code"]), d])), codes = new Map((await providersOf(c)).map((p) => [String(p["code"]).toUpperCase(), String(p["id"])])), now = await resolveTargets(pool, c.pid, today());
  const errors: { path: string; code: string; message: string }[] = [], todo: { indicatorCode: string; providerId: string | null; value: number; effectiveFrom: string; note: string }[] = [], seen = new Set<string>();
  for (const [i, r] of rows.entries()) {
    const line = `Row ${i + 2}`, bad = (message: string) => errors.push({ path: line, code: "INVALID", message }), raw = (r["target"] ?? "").trim(), code = (r["indicator_code"] ?? "").trim(), who = (r["provider_code"] ?? "").trim().toUpperCase();
    if (!raw) continue;
    const d = defs.get(code), providerId = who === "PROJECT" ? null : codes.get(who), value = Number(raw), from = (r["effective_from"] ?? "").trim() ? parseFormDate(r["effective_from"]!) : today();
    if (!d) bad(`Indicator "${code}" does not exist.`);
    else if (providerId === undefined) bad(`Provider "${who}" does not exist. Use PROJECT for the project default.`);
    else if (!Number.isFinite(value) || value < 0 || value > 10_000_000 || (d["unit"] === "percent" && value > 100)) bad(`Target "${raw}" is not possible for ${d["name"]}.`);
    else if (!from) bad("Write the date as DD/MM/YYYY.");
    else if (seen.has(`${code}:${who}:${from}`)) bad("The same indicator, provider and date is in the file twice.");
    else {
      seen.add(`${code}:${who}:${from}`);
      const own = now.filter((t) => t["code"] === code && (providerId === null ? t["providerId"] === null : t["providerId"] !== null && String(t["providerId"]) === providerId)).at(-1);
      if (!own || Number(own["value"]) !== value) todo.push({ indicatorCode: code, providerId, value, effectiveFrom: from, note: (r["note"] ?? "").trim().slice(0, 480) || "Imported from Excel" });
    }
  }
  if (errors.length) throw new DomainError(422, "VALIDATION", `${errors.length} rows need attention. Nothing was saved.`, errors.slice(0, 200));
  for (const t of todo) await setTarget(c, t);
  return { saved: todo.length, unchanged: rows.length - todo.length };
}
