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

/**
 * AdminDashboardPageQuery
 *
 * Server-side composition for admin dashboard page.
 * Fetches dashboard statistics from API and transforms to ViewData.
 *
 * Follows Clean Architecture: Uses builders for transformation.
 */
export class AdminDashboardPageQuery implements PageQuery<AdminDashboardViewData, void, PresentationError> {
  async execute(): Promise<Result<AdminDashboardViewData, PresentationError>> {
    // Manual construction: Service creates its own dependencies
    const adminService = new AdminService();

    // Fetch dashboard stats
    const apiDtoResult = await adminService.getDashboardStats();

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

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

    return Result.ok(output);
  }

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