import test from "node:test";
import assert from "node:assert/strict";

import { estaEsgotado, estoqueLimitaAVenda, semEsgotados } from "./loja/regras-da-loja.ts";

/*
  "Permitir estoque negativo" ligado: a loja vende como se houvesse saldo. O
  estoque so trava a venda (botao "Indisponivel", selo "Esgotado", sumir da
  lista na regra "esconder") quando o produto controla estoque e NAO permite
  ficar negativo.
*/

test("so limita quando controla estoque e nao permite negativo", () => {
  assert.equal(estoqueLimitaAVenda({ track_inventory: true, allow_negative_stock: false }), true);
  assert.equal(estoqueLimitaAVenda({ track_inventory: true, allow_negative_stock: true }), false);
  assert.equal(estoqueLimitaAVenda({ track_inventory: false, allow_negative_stock: false }), false);
  assert.equal(estoqueLimitaAVenda({ track_inventory: false, allow_negative_stock: true }), false);
  /* Sem a marcacao no dado (grade antiga), vale o comportamento de sempre. */
  assert.equal(estoqueLimitaAVenda({ track_inventory: true }), true);
  assert.equal(estoqueLimitaAVenda(null), false);
  assert.equal(estoqueLimitaAVenda(undefined), false);
});

test("zerado com estoque negativo permitido nao esta esgotado", () => {
  assert.equal(estaEsgotado({ track_inventory: true, allow_negative_stock: true, stock: 0 }), false);
  assert.equal(estaEsgotado({ track_inventory: true, allow_negative_stock: true, stock: -4 }), false);
  assert.equal(estaEsgotado({ track_inventory: true, allow_negative_stock: true, stock: "-4" }), false);
});

test("zerado sem a permissao continua esgotado", () => {
  assert.equal(estaEsgotado({ track_inventory: true, allow_negative_stock: false, stock: 0 }), true);
  assert.equal(estaEsgotado({ track_inventory: true, allow_negative_stock: false, stock: "0" }), true);
  assert.equal(estaEsgotado({ track_inventory: true, stock: null }), true);
  assert.equal(estaEsgotado({ track_inventory: true, allow_negative_stock: false, stock: 3 }), false);
  assert.equal(estaEsgotado({ track_inventory: false, allow_negative_stock: false, stock: 0 }), false);
});

test("esconder esgotados nao some com quem vende sem saldo", () => {
  const lista = [
    { id: "a", track_inventory: true, allow_negative_stock: true, stock: 0 },
    { id: "b", track_inventory: true, allow_negative_stock: false, stock: 0 },
    { id: "c", track_inventory: false, allow_negative_stock: false, stock: 0 },
    { id: "d", track_inventory: true, allow_negative_stock: false, stock: 2 },
  ];
  assert.deepEqual(
    semEsgotados(lista).map((produto) => produto.id),
    ["a", "c", "d"]
  );
});
