// Map CSM identity/role -> AOM shapes. Key idea (plan §9.6/§9.7): reuse AOM's
// existing RBAC. We only need to derive an AOM Role.code; resolveRoleByUserField
// + requirePermission then work exactly as before.
import type { CsmUser } from './auth';

// Active AOM role codes (see backend/src/scripts/seed-roles.ts).
export const AOM_ROLE_CODES = ['ADMIN', 'OM_MANAGER', 'TECHNICIAN', 'HSE_OFFICER', 'ASSET_OWNER'] as const;
export type AomRoleCode = (typeof AOM_ROLE_CODES)[number];

function deptText(user: any): string {
  const d = user?.department;
  if (!d) return '';
  return typeof d === 'string' ? d : d?.name || '';
}

/**
 * Resolve the AOM role code for a CSM user.
 * 1) Prefer explicit webtool grant roles (CSM already stores AOM codes) — plan §9.7.
 * 2) Fall back to a heuristic over CSM role/roles/department/position — plan §9.6.
 * Never returns empty: unknown -> lowest role (TECHNICIAN).
 */
export function mapCsmRoleToAomCode(user: any, webtoolRoles?: string[]): AomRoleCode {
  if (Array.isArray(webtoolRoles)) {
    const hit = webtoolRoles
      .map((r) => String(r).toUpperCase())
      .find((r) => (AOM_ROLE_CODES as readonly string[]).includes(r));
    if (hit) return hit as AomRoleCode;
  }

  const text = [
    user?.role,
    ...(Array.isArray(user?.roles) ? user.roles : []),
    deptText(user),
    user?.position,
  ]
    .filter(Boolean)
    .join(' ')
    .toLowerCase();

  if (/admin|giám đốc|director|quản trị/.test(text)) return 'ADMIN';
  if (/hse|an toàn|safety|môi trường/.test(text)) return 'HSE_OFFICER';
  if (/asset owner|chủ tài sản|chủ sở hữu|owner/.test(text)) return 'ASSET_OWNER';
  if (/manager|quản lý|trưởng|lead|giám sát|supervisor/.test(text)) return 'OM_MANAGER';
  return 'TECHNICIAN';
}

// AOM Role.code -> display name (matches backend/src/scripts/seed-roles.ts).
const CODE_TO_NAME: Record<string, string> = {
  ADMIN: 'System Administrator',
  OM_MANAGER: 'O&M Manager',
  TECHNICIAN: 'Technician',
  HSE_OFFICER: 'HSE Officer',
  ASSET_OWNER: 'Asset Owner',
};

/** CSM member -> AOM directory user shape (mirrors what /api/users used to return). */
export function mapCsmMemberToAomUser(m: any): Record<string, any> {
  const status = m?.status || 'Active';
  // Prefer the webtool grant role (present when the directory was queried with
  // granted=true) so the AOM role reflects what CSM actually granted for AOM.
  const code = mapCsmRoleToAomCode(m, m?.webtool?.roles);
  return {
    _id: m?.id,
    csmUserId: m?.id,
    name: m?.name,
    email: m?.email,
    phone: m?.phone,
    // role = display name; roleCode = the code the frontend RBAC filters check.
    role: CODE_TO_NAME[code] || code,
    roleCode: code,
    department: deptText(m),
    status,
    active: status === 'Active',
    scope: ['Tất cả'],
    source: 'CSM',
  };
}

/** CSM verify user -> AOM session user (for login response + /auth/me). */
export function buildCsmSessionUser(user: CsmUser, roleCode: string): Record<string, any> {
  return {
    _id: String(user?.id || ''),
    csmUserId: String(user?.id || ''),
    email: user?.email,
    name: user?.name,
    phone: user?.phone,
    role: roleCode,
    department: deptText(user),
    status: 'Active',
    scope: ['Tất cả'],
    source: 'CSM',
  };
}
