import { AdminUser } from "@/lib/admin/db";
import { SUB_ADMIN_ROLES } from "@/lib/admin/permissions";

/**
 * Maps system and custom roles to professional editorial author titles. This is
 * only a FALLBACK job title — the user's own `jobTitle` profile field takes
 * precedence (Role and Job Title are different concepts, per spec §6/§48).
 */
export function getAuthorRoleLabel(role: string, level?: string): string {
  if (level === "MAIN_ADMIN" || role === "MAIN_ADMIN") {
    return "Main Administrator";
  }

  const predefined = SUB_ADMIN_ROLES.find((r) => r.id === role);
  if (predefined) {
    return predefined.label;
  }

  // If custom role, format cleanly
  return role
    .replace(/^role_/i, "")
    .replace(/_[a-z0-9]+$/i, "")
    .replace(/_/g, " ")
    .replace(/\b\w/g, (c) => c.toUpperCase());
}

/**
 * Maps author initials and colors for UI badges/avatars.
 */
export function getAuthorAvatar(name: string): { avatarText: string; avatarColor: string } {
  const parts = name.trim().split(/\s+/).filter(Boolean);
  const initials =
    parts.length >= 2
      ? `${parts[0][0]}${parts[1][0]}`.toUpperCase()
      : name.slice(0, 2).toUpperCase();

  const colors = [
    "from-blue-600 to-indigo-600",
    "from-purple-600 to-pink-600",
    "from-emerald-600 to-teal-600",
    "from-amber-600 to-orange-600",
    "from-cyan-600 to-blue-600",
  ];

  const charCode = (name.charCodeAt(0) || 0) + (name.charCodeAt(1) || 0);
  const avatarColor = colors[charCode % colors.length];

  return { avatarText: initials, avatarColor };
}

export interface ResolvedAuthor {
  id: string;
  name: string;
  displayName: string;
  email: string;
  professionalEmail?: string;
  role: string; // job title label (real jobTitle, else role label)
  systemRole: string;
  level: string;
  avatarText: string;
  avatarColor: string;
  avatarUrl: string | null;
  bio: string;
  longBio: string;
  location: string;
  profileSlug: string;
  socials: {
    linkedin?: string;
    instagram?: string;
    x?: string;
    website?: string;
    github?: string;
    youtube?: string;
  };
}

/**
 * Resolves the public author record from an admin/sub-admin account, using the
 * account's REAL profile fields (never a fabricated bio). Falls back only where
 * a profile field has not been filled in yet, so a freshly-created account still
 * renders sensibly while the owner completes their profile.
 */
export function resolveAuthorFromUser(u: AdminUser): ResolvedAuthor {
  const roleLabel = getAuthorRoleLabel(u.role, u.level);
  const displayName = (u.displayName || u.name || "").trim();
  const { avatarText, avatarColor } = getAuthorAvatar(displayName || u.name);

  const profileSlug =
    u.authorSlug ||
    (displayName || u.name || "author")
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, "-")
      .replace(/^-+|-+$/g, "");

  return {
    id: u.id,
    name: u.name,
    displayName: displayName || u.name,
    email: u.email,
    professionalEmail: u.professionalEmail || undefined,
    // Prefer the real job title; fall back to the role label (never the RBAC role id).
    role: (u.jobTitle && u.jobTitle.trim()) || roleLabel,
    systemRole: u.role,
    level: u.level,
    avatarText,
    avatarColor,
    avatarUrl: u.avatarUrl || null,
    // Real bios only — empty string when unset (callers decide fallback copy).
    bio: (u.shortBio || "").trim(),
    longBio: (u.longBio || "").trim(),
    location: (u.location || "").trim(),
    profileSlug,
    socials: {
      linkedin: u.socials?.linkedin || undefined,
      instagram: u.socials?.instagram || undefined,
      x: u.socials?.x || undefined,
      website: u.socials?.website || undefined,
      github: u.socials?.github || undefined,
      youtube: u.socials?.youtube || undefined,
    },
  };
}

/** Compact author record embedded on posts (BlogAuthor shape), from a profile. */
export function toBlogAuthor(u: AdminUser) {
  const a = resolveAuthorFromUser(u);
  return {
    name: a.displayName,
    role: a.role,
    avatarText: a.avatarText,
    avatarColor: a.avatarColor,
    bio: a.bio,
    profileSlug: a.profileSlug,
  };
}
