import { Result } from '@/lib/contracts/Result';
import { LeagueService } from '@/lib/services/leagues/LeagueService';
import { LeaguesApiClient } from '@/lib/api/leagues/LeaguesApiClient';
import { ConsoleErrorReporter } from '@/lib/infrastructure/logging/ConsoleErrorReporter';
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';

/**
 * ScheduleAdminMutation
 * 
 * Framework-agnostic mutation for schedule administration operations.
 * Can be called from Server Actions or other contexts.
 */
export class ScheduleAdminMutation {
  private service: LeagueService;

  constructor() {
    // Manual wiring for serverless
    const baseUrl = process.env.NEXT_PUBLIC_API_URL || '';
    const errorReporter = new ConsoleErrorReporter();
    const logger = new ConsoleLogger();
    new LeaguesApiClient(baseUrl, errorReporter, logger);
    
    this.service = new LeagueService();
  }

  async publishSchedule(leagueId: string, seasonId: string): Promise<Result<void, string>> {
    try {
      await this.service.publishAdminSchedule(leagueId, seasonId);
      return Result.ok(undefined);
    } catch (error) {
      console.error('publishSchedule failed:', error);
      return Result.err('Failed to publish schedule');
    }
  }

  async unpublishSchedule(leagueId: string, seasonId: string): Promise<Result<void, string>> {
    try {
      await this.service.unpublishAdminSchedule(leagueId, seasonId);
      return Result.ok(undefined);
    } catch (error) {
      console.error('unpublishSchedule failed:', error);
      return Result.err('Failed to unpublish schedule');
    }
  }

  async createRace(leagueId: string, seasonId: string, input: { track: string; car: string; scheduledAtIso: string }): Promise<Result<void, string>> {
    try {
      await this.service.createAdminScheduleRace(leagueId, seasonId, input);
      return Result.ok(undefined);
    } catch (error) {
      console.error('createRace failed:', error);
      return Result.err('Failed to create race');
    }
  }

  async updateRace(leagueId: string, seasonId: string, raceId: string, input: Partial<{ track: string; car: string; scheduledAtIso: string }>): Promise<Result<void, string>> {
    try {
      await this.service.updateAdminScheduleRace(leagueId, seasonId, raceId, input);
      return Result.ok(undefined);
    } catch (error) {
      console.error('updateRace failed:', error);
      return Result.err('Failed to update race');
    }
  }

  async deleteRace(leagueId: string, seasonId: string, raceId: string): Promise<Result<void, string>> {
    try {
      await this.service.deleteAdminScheduleRace(leagueId, seasonId, raceId);
      return Result.ok(undefined);
    } catch (error) {
      console.error('deleteRace failed:', error);
      return Result.err('Failed to delete race');
    }
  }
}