import { FeatureFlagService } from '@/lib/feature/FeatureFlagService';

// API Clients
import { RacesApiClient } from '@/lib/api/races/RacesApiClient';
import { LeaguesApiClient } from '@/lib/api/leagues/LeaguesApiClient';
import { TeamsApiClient } from '@/lib/api/teams/TeamsApiClient';

// Services
import { SessionService } from '@/lib/services/auth/SessionService';

// Infrastructure
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
import { ConsoleErrorReporter } from '@/lib/infrastructure/logging/ConsoleErrorReporter';
import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';

// DTO types
import { Result } from '@/lib/contracts/Result';
import type { Service } from '@/lib/contracts/services/Service';
import type { HomeDataDTO } from '@/lib/types/dtos/HomeDataDTO';

import { DateDisplay } from '@/lib/display-objects/DateDisplay';

/**
 * HomeService
 * 
 * @server-safe
 */
export class HomeService implements Service {
  async getHomeData(): Promise<Result<HomeDataDTO, Error>> {
    try {
      // Manual wiring: construct dependencies explicitly
      const baseUrl = getWebsiteApiBaseUrl();
      const errorReporter = new ConsoleErrorReporter();
      const logger = new ConsoleLogger();

      // Construct API clients
      const racesApiClient = new RacesApiClient(baseUrl, errorReporter, logger);
      const leaguesApiClient = new LeaguesApiClient(baseUrl, errorReporter, logger);
      const teamsApiClient = new TeamsApiClient(baseUrl, errorReporter, logger);

      // Get feature flags
      const featureService = await FeatureFlagService.fromAPI();
      const isAlpha = featureService.isEnabled('alpha_features');

      // Get home discovery data (manual implementation)
      const [racesDto, leaguesDto, teamsDto] = await Promise.all([
        racesApiClient.getPageData(),
        leaguesApiClient.getAllWithCapacity(),
        teamsApiClient.getAll(),
      ]);

      // Return DTOs directly (no ViewModels)
      return Result.ok({
        isAlpha,
        upcomingRaces: racesDto.races.slice(0, 4).map(r => ({
          id: r.id,
          track: r.track,
          car: r.car,
          formattedDate: DateDisplay.formatShort(r.scheduledAt),
        })),
        topLeagues: leaguesDto.leagues.slice(0, 4).map(l => ({
          id: l.id,
          name: l.name,
          description: l.description,
        })),
        teams: teamsDto.teams.slice(0, 4).map(t => ({
          id: t.id,
          name: t.name,
          description: t.description,
          logoUrl: t.logoUrl,
        })),
      });
    } catch (err) {
      return Result.err(err instanceof Error ? err : new Error('Failed to get home data'));
    }
  }

  async shouldRedirectToDashboard(): Promise<boolean> {
    const sessionService = new SessionService();
    const result = await sessionService.getSession();
    return result.isOk() && !!result.unwrap();
  }
}
