// ═══════════════════════════════════════════════════
//  app/lib/mappers/user.mapper.ts
// ═══════════════════════════════════════════════════

import { UserRaw, UserMapped } from "./../types/user.types";

/**
 * Maps a raw API user response into a normalized UserMapped shape
 * used by all components in the users module.
 */
export function mapUser(raw: UserRaw, index: number): UserMapped {
  return {
    sno: index + 1,
    id: raw.id,
    firstName: raw.firstName || "",
    lastName: raw.lastName || "",
    fullName: `${raw.firstName || ""} ${raw.lastName || ""}`.trim(),
    email: raw.email || "",
    isActive: raw.isActive ?? true,
    isEmailVerified: raw.isEmailVerified ?? false,
    isApprovedByAdmin: raw.isApprovedByAdmin ?? false,
    status: raw.status || "pending",
    roles: raw.roles || [],
    permissions: raw.permissions || [],
    created_at: raw.created_at || "",
    updated_at: raw.updated_at || "",
  };
}

/**
 * Maps an array of raw users
 */
export function mapUsers(rawList: UserRaw[]): UserMapped[] {
  return rawList.map((u, i) => mapUser(u, i));
}

/**
 * Returns a user's display status label + color
 */
export function getUserStatus(user: UserMapped): {
  label: string;
  color: string;
  bg: string;
} {
  if (user.status === "rejected")
    return { label: "REJECTED",  color: "#dc2626", bg: "#fee2e2" };
  if (!user.isEmailVerified)
    return { label: "UNVERIFIED", color: "#d97706", bg: "#fef3c7" };
  if (!user.isApprovedByAdmin)
    return { label: "PENDING",   color: "#1d4ed8", bg: "#dbeafe" };
  if (!user.isActive)
    return { label: "INACTIVE",  color: "#9ca3af", bg: "#f3f4f6" };
  return   { label: "ACTIVE",    color: "#16a34a", bg: "#dcfce7" };
}

/**
 * Formats a date string into DD-MMM-YYYY
 */
export function formatUserDate(dateString: string): string {
  if (!dateString) return "—";
  try {
    return new Date(dateString)
      .toLocaleDateString("en-GB", {
        day: "2-digit",
        month: "short",
        year: "numeric",
      })
      .replace(/ /g, "-");
  } catch {
    return dateString;
  }
}

/**
 * Returns avatar initials from a user
 */
export function getUserInitials(user: UserMapped | UserRaw): string {
  return `${user.firstName?.[0] ?? ""}${user.lastName?.[0] ?? ""}`.toUpperCase() || "?";
}

/**
 * Generates a deterministic avatar background color from user ID
 */
export function getUserAvatarColor(id: number): string {
  const hue = (id * 47) % 360;
  return `hsl(${hue}, 60%, 55%)`;
}
