import { z } from "zod"

export const MACHINE_CTX_COOKIE = "machine_ctx"

const machineCookieSchema = z.object({
  machineId: z.string(),
  persona: z.string().nullable().optional(),
  assignedUserId: z.string().nullable().optional(),
  assignedUserEmail: z.string().nullable().optional(),
  assignedUserName: z.string().nullable().optional(),
  assignedUserRole: z.string().nullable().optional(),
})

const collaboratorSchema = z
  .object({
    email: z.string().email(),
    name: z.string().optional(),
    role: z.string().optional(),
  })
  .transform(({ email, name, role }) => {
    const trimmedRole = role?.trim().toLowerCase()
    const normalizedRole =
      trimmedRole === "manager"
        ? "manager"
        : trimmedRole === "collaborator"
          ? "collaborator"
          : null

    const normalizedName = typeof name === "string" ? name.trim() || null : null

    return {
      email: email.trim().toLowerCase(),
      name: normalizedName,
      role: normalizedRole,
    }
  })

const metadataSchema = z
  .object({
    collaborator: collaboratorSchema,
  })
  .passthrough()

export type MachineContextCookiePayload = z.infer<typeof machineCookieSchema>
export type CollaboratorMetadata = z.output<typeof collaboratorSchema>

export function parseMachineCookie(value: string | null | undefined): MachineContextCookiePayload | null {
  if (!value) return null
  try {
    const json = Buffer.from(value, "base64url").toString("utf8")
    const parsed = JSON.parse(json)
    return machineCookieSchema.parse(parsed)
  } catch {
    return null
  }
}

export function serializeMachineCookie(payload: MachineContextCookiePayload): string {
  return Buffer.from(JSON.stringify(machineCookieSchema.parse(payload))).toString("base64url")
}

export function extractCollaboratorFromMetadata(metadata: unknown): CollaboratorMetadata | null {
  if (!metadata) return null
  const parsed = metadataSchema.safeParse(metadata)
  if (!parsed.success) {
    return null
  }
  return parsed.data.collaborator
}

