"use client";

import { Badge } from "@workspace/ui/components/badge";
import { parseDeviceType } from "@workspace/ui/utils/device";

type UserDeviceWithDeviceNo = API.UserDevice & {
  device_no?: string;
};

type UserIdentifierUser = {
  auth_methods?: API.UserAuthMethod[];
  user_devices?: UserDeviceWithDeviceNo[];
};

type UserIdentifierParts = {
  authLabel: "(D)" | "(E)";
  deviceBadge?: string;
  identifier: string;
  isDevice: boolean;
};

export function getUserIdentifierParts(
  user?: UserIdentifierUser
): UserIdentifierParts {
  const method = user?.auth_methods?.[0];
  const firstDevice = user?.user_devices?.[0] as
    | UserDeviceWithDeviceNo
    | undefined;
  const isDevice = method?.auth_type === "device";
  const rawIdentifier = method?.auth_identifier || "";
  const identifier = isDevice
    ? firstDevice?.device_no || rawIdentifier
    : rawIdentifier;

  return {
    authLabel: isDevice ? "(D)" : "(E)",
    deviceBadge: parseDeviceType(firstDevice?.user_agent || ""),
    identifier,
    isDevice,
  };
}

export function UserIdentifier({
  className,
  user,
}: {
  className?: string;
  user?: UserIdentifierUser;
}) {
  const { authLabel, deviceBadge, identifier, isDevice } =
    getUserIdentifierParts(user);

  return (
    <div className={className}>
      {deviceBadge ? (
        <Badge className="mr-1" variant="secondary">
          {deviceBadge}
        </Badge>
      ) : null}
      <span className="mr-1 font-mono text-xs uppercase">{authLabel}</span>
      <span title={isDevice ? identifier : undefined}>
        {identifier || "--"}
      </span>
    </div>
  );
}
