import type { AuthUser } from '@/lib/auth-service';
import type { Permission, Role } from '@/lib/permissions';
import { getPermissionsForRoles } from '@/lib/permissions';
import { getPrimaryRole } from '@/auth/primaryRole';

/** Mirrors AuthContext `User` — defined here to avoid circular imports. */
export type AuthSessionUser = {
  id: string;
  email: string;
  name?: string;
  phone?: string | null;
  roles: Role[];
  availableRoles: Role[];
  permissions: Permission[];
};

export function buildUserFromAuthPayload(authUser: AuthUser): AuthSessionUser | null {
  const availableRoles = (authUser.roles?.length ? authUser.roles : ['viewer']) as Role[];
  const activeRole = getPrimaryRole(availableRoles);

  return {
    id: authUser.id,
    email: authUser.email,
    name: authUser.name,
    phone: authUser.phone ?? null,
    roles: [activeRole],
    availableRoles,
    permissions: getPermissionsForRoles([activeRole]),
  };
}
