import { PageQuery } from '@/lib/contracts/page-queries/PageQuery';
import { Result } from '@/lib/contracts/Result';
import { AdminService } from '@/lib/services/admin/AdminService';
import { AdminUsersViewDataBuilder } from '@/lib/builders/view-data/AdminUsersViewDataBuilder';
import type { AdminUsersViewData } from '@/lib/view-data/AdminUsersViewData';
import { PresentationError, mapToPresentationError } from '@/lib/contracts/page-queries/PresentationError';

/**
 * AdminUsersPageQuery
 *
 * Server-side composition for admin users page.
 * Fetches user list from API and transforms to ViewData.
 */
export class AdminUsersPageQuery implements PageQuery<AdminUsersViewData, void> {
  async execute(): Promise<Result<AdminUsersViewData, PresentationError>> {
    try {
      // Manual construction: Service creates its own dependencies
      const adminService = new AdminService();

      // Fetch user list via service
       const apiDtoResult = await adminService.listUsers();

      if (apiDtoResult.isErr()) {
        return Result.err(mapToPresentationError(apiDtoResult.getError()));
      }

      // Transform to ViewData using builder
      const output = AdminUsersViewDataBuilder.build(apiDtoResult.unwrap());

      return Result.ok(output);
    } catch (error) {
      console.error('AdminUsersPageQuery failed:', error);
      
      if (error instanceof Error && (error.message.includes('403') || error.message.includes('401'))) {
        return Result.err('notFound');
      }
      
      return Result.err('serverError');
    }
  }

  // Static method to avoid object construction in server code
  static async execute(): Promise<Result<AdminUsersViewData, PresentationError>> {
    const queryInstance = new AdminUsersPageQuery();
    return queryInstance.execute();
  }
}