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

import { normalizeCustomFieldInputs } from "../src/lib/ticket-form-helpers"
import type { TicketFormFieldDefinition } from "../src/lib/ticket-form-types"
import type { Id } from "../convex/_generated/dataModel"

describe("ticket form helpers", () => {
  const baseFields: TicketFormFieldDefinition[] = [
    {
      id: "field-nome",
      key: "nome",
      label: "Nome",
      type: "text",
      required: true,
      description: "",
      options: [],
    },
    {
      id: "field-data",
      key: "data",
      label: "Data",
      type: "date",
      required: false,
      description: "",
      options: [],
    },
    {
      id: "field-numero",
      key: "numero",
      label: "Número",
      type: "number",
      required: true,
      description: "",
      options: [],
    },
    {
      id: "field-select",
      key: "tipo",
      label: "Tipo",
      type: "select",
      required: true,
      description: "",
      options: [
        { value: "nova", label: "Nova contratação" },
        { value: "substituicao", label: "Substituição" },
      ],
    },
  ]

  it("normalizes values for required fields", () => {
    const result = normalizeCustomFieldInputs(baseFields, {
      "field-nome": " Ana Silva ",
      "field-numero": "123",
      "field-select": "nova",
    })

    expect(result.ok).toBe(true)
    if (result.ok) {
      expect(result.payload).toEqual([
        { fieldId: "field-nome" as Id<"ticketFields">, value: "Ana Silva" },
        { fieldId: "field-numero" as Id<"ticketFields">, value: 123 },
        { fieldId: "field-select" as Id<"ticketFields">, value: "nova" },
      ])
    }
  })

  it("fails when a required field is empty", () => {
    const result = normalizeCustomFieldInputs(baseFields, {
      "field-nome": "   ",
    })

    expect(result.ok).toBe(false)
    if (!result.ok) {
      expect(result.message).toContain("Nome")
    }
  })
})
