import type { UserListResponse } from '@/lib/types/admin';
import { AdminUsersViewData } from '@/lib/view-data/AdminUsersViewData';

/**
 * AdminUsersViewDataBuilder
 * 
 * Server-side builder that transforms API DTO
 * into ViewData for the AdminUsersTemplate.
 * 
 * Deterministic, side-effect free.
 */
export class AdminUsersViewDataBuilder {
  static build(apiDto: UserListResponse): AdminUsersViewData {
    const users = apiDto.users.map(user => ({
      id: user.id,
      email: user.email,
      displayName: user.displayName,
      roles: user.roles,
      status: user.status,
      isSystemAdmin: user.isSystemAdmin,
      createdAt: typeof user.createdAt === 'string' ? user.createdAt : (user.createdAt as unknown as Date).toISOString(),
      updatedAt: typeof user.updatedAt === 'string' ? user.updatedAt : (user.updatedAt as unknown as Date).toISOString(),
      lastLoginAt: user.lastLoginAt ? (typeof user.lastLoginAt === 'string' ? user.lastLoginAt : (user.lastLoginAt as unknown as Date).toISOString()) : undefined,
      primaryDriverId: user.primaryDriverId,
    }));

    return {
      users,
      total: apiDto.total,
      page: apiDto.page,
      limit: apiDto.limit,
      totalPages: apiDto.totalPages,
      // Pre-computed derived values for template
      activeUserCount: users.filter(u => u.status === 'active').length,
      adminCount: users.filter(u => u.isSystemAdmin).length,
    };
  }
}