import { describe, expect, it } from "bun:test"

import type { Id } from "../convex/_generated/dataModel"
import { applyChecklistTemplateToItems, checklistBlocksResolution } from "../convex/ticketChecklist"

describe("convex.ticketChecklist", () => {
  it("aplica template no checklist de forma idempotente", () => {
    const now = 123
    const template = {
      _id: "tpl_1" as Id<"ticketChecklistTemplates">,
      items: [
        { id: "i1", text: "Validar backup", required: true },
        { id: "i2", text: "Reiniciar serviço" }, // required default true
      ],
    }

    const generatedIds = ["c1", "c2"]
    let idx = 0
    const first = applyChecklistTemplateToItems([], template, {
      now,
      actorId: "user_1" as Id<"users">,
      generateId: () => generatedIds[idx++]!,
    })

    expect(first.added).toBe(2)
    expect(first.checklist).toHaveLength(2)
    expect(first.checklist[0]).toEqual(
      expect.objectContaining({
        id: "c1",
        text: "Validar backup",
        done: false,
        required: true,
        templateId: template._id,
        templateItemId: "i1",
        createdAt: now,
        createdBy: "user_1",
      })
    )
    expect(first.checklist[1]).toEqual(
      expect.objectContaining({
        id: "c2",
        text: "Reiniciar serviço",
        required: true,
        templateItemId: "i2",
      })
    )

    const second = applyChecklistTemplateToItems(first.checklist, template, {
      now: now + 1,
      actorId: "user_2" as Id<"users">,
      generateId: () => "should_not_add",
    })
    expect(second.added).toBe(0)
    expect(second.checklist).toHaveLength(2)
  })

  it("bloqueia encerramento quando há item obrigatório pendente", () => {
    expect(
      checklistBlocksResolution([
        { id: "1", text: "Obrigatório", done: false, required: true },
      ])
    ).toBe(true)

    expect(
      checklistBlocksResolution([
        { id: "1", text: "Opcional", done: false, required: false },
      ])
    ).toBe(false)

    expect(
      checklistBlocksResolution([
        { id: "1", text: "Obrigatório", done: true, required: true },
      ])
    ).toBe(false)
  })
})

