import { describe, expect, it } from "vitest"

import { computeInviteStatus, normalizeInvite, normalizeRoleOption } from "@/server/invite-utils"

const baseInvite = {
  id: "invite-1",
  email: "user@sistema.dev",
  name: "Usuário Teste",
  role: "agent",
  tenantId: "tenant-1",
  token: "token",
  status: "pending",
  expiresAt: new Date(Date.now() + 60_000),
  createdAt: new Date(),
  updatedAt: new Date(),
  createdById: "admin-1",
  acceptedAt: null,
  acceptedById: null,
  revokedAt: null,
  revokedById: null,
  revokedReason: null,
} as const

describe("invite-utils", () => {
  it("computes pending status when invite is valid", () => {
    const status = computeInviteStatus(baseInvite)
    expect(status).toBe("pending")
  })

  it("computes expired status when invite is past expiration", () => {
    const expiredInvite = { ...baseInvite, expiresAt: new Date(Date.now() - 1) }
    const status = computeInviteStatus(expiredInvite)
    expect(status).toBe("expired")
  })

  it("honors revoked status regardless of expiration", () => {
    const revoked = { ...baseInvite, status: "revoked" as const, expiresAt: new Date(Date.now() - 1) }
    const status = computeInviteStatus(revoked)
    expect(status).toBe("revoked")
  })

  it("normalizes invite payload with defaults", () => {
    const normalized = normalizeInvite({ ...baseInvite, events: [] })
    expect(normalized.email).toBe(baseInvite.email)
    expect(normalized.status).toBe("pending")
    expect(normalized.events).toHaveLength(0)
  })

  it("normalizes role falling back to agent", () => {
    expect(normalizeRoleOption("admin")).toBe("admin")
    expect(normalizeRoleOption("unknown")).toBe("agent")
  })
})
