import { PageQuery } from '@/lib/contracts/page-queries/PageQuery';
import { Result } from '@/lib/contracts/Result';
import { DashboardViewDataBuilder } from '@/lib/builders/view-data/DashboardViewDataBuilder';
import type { DashboardViewData } from '@/lib/view-data/DashboardViewData';
import { DashboardService } from '@/lib/services/analytics/DashboardService';
import { mapToPresentationError, type PresentationError } from '@/lib/contracts/page-queries/PresentationError';

/**
 * Dashboard page query
 * Returns Result<DashboardViewData, PresentationError>
 * No DI container usage - constructs dependencies explicitly
 */
export class DashboardPageQuery implements PageQuery<DashboardViewData, void, PresentationError> {
  async execute(): Promise<Result<DashboardViewData, PresentationError>> {
    // Manual wiring: Service creates its own dependencies
    const dashboardService = new DashboardService();
    
    // Fetch data using service
    const serviceResult = await dashboardService.getDashboardOverview();
    
    if (serviceResult.isErr()) {
      // Map domain errors to presentation errors using helper
      return Result.err(mapToPresentationError(serviceResult.getError()));
    }

    // Transform to ViewData using builder
    const apiDto = serviceResult.unwrap();
    const dashboardView = DashboardViewDataBuilder.build(apiDto);
    return Result.ok(dashboardView);
  }

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