'use server';

import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import { Result } from '@/lib/contracts/Result';
import { ScheduleAdminMutation } from '@/lib/mutations/leagues/ScheduleAdminMutation';
import { RacesApiClient } from '@/lib/api/races/RacesApiClient';
import { routes } from '@/lib/routing/RouteConfig';
import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';
import { ConsoleErrorReporter } from '@/lib/infrastructure/logging/ConsoleErrorReporter';
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';

// eslint-disable-next-line gridpilot-rules/server-actions-interface
export async function publishScheduleAction(leagueId: string, seasonId: string): Promise<Result<void, string>> {
  const mutation = new ScheduleAdminMutation();
  const result = await mutation.publishSchedule(leagueId, seasonId);
  
  if (result.isOk()) {
    revalidatePath(routes.league.schedule(leagueId));
  }
  
  return result;
}

// eslint-disable-next-line gridpilot-rules/server-actions-interface
export async function unpublishScheduleAction(leagueId: string, seasonId: string): Promise<Result<void, string>> {
  const mutation = new ScheduleAdminMutation();
  const result = await mutation.unpublishSchedule(leagueId, seasonId);
  
  if (result.isOk()) {
    revalidatePath(routes.league.schedule(leagueId));
  }
  
  return result;
}

// eslint-disable-next-line gridpilot-rules/server-actions-interface
export async function createRaceAction(
  leagueId: string,
  seasonId: string,
  input: { track: string; car: string; scheduledAtIso: string }
): Promise<Result<void, string>> {
  const mutation = new ScheduleAdminMutation();
  const result = await mutation.createRace(leagueId, seasonId, input);
  
  if (result.isOk()) {
    revalidatePath(routes.league.schedule(leagueId));
  }
  
  return result;
}

// eslint-disable-next-line gridpilot-rules/server-actions-interface
export async function updateRaceAction(
  leagueId: string,
  seasonId: string,
  raceId: string,
  input: Partial<{ track: string; car: string; scheduledAtIso: string }>
): Promise<Result<void, string>> {
  const mutation = new ScheduleAdminMutation();
  const result = await mutation.updateRace(leagueId, seasonId, raceId, input);
  
  if (result.isOk()) {
    revalidatePath(routes.league.schedule(leagueId));
  }
  
  return result;
}

// eslint-disable-next-line gridpilot-rules/server-actions-interface
export async function deleteRaceAction(leagueId: string, seasonId: string, raceId: string): Promise<Result<void, string>> {
  const mutation = new ScheduleAdminMutation();
  const result = await mutation.deleteRace(leagueId, seasonId, raceId);
  
  if (result.isOk()) {
    revalidatePath(routes.league.schedule(leagueId));
  }
  
  return result;
}

// eslint-disable-next-line gridpilot-rules/server-actions-interface
export async function registerForRaceAction(raceId: string, leagueId: string, driverId: string): Promise<Result<void, string>> {
  try {
    const baseUrl = getWebsiteApiBaseUrl();
    const apiClient = new RacesApiClient(
      baseUrl,
      new ConsoleErrorReporter(),
      new ConsoleLogger()
    );
    
    await apiClient.register(raceId, { raceId, leagueId, driverId });
    
    // Revalidate the schedule page to show updated registration status
    revalidatePath(routes.league.schedule(leagueId));
    
    return Result.ok(undefined);
  } catch (error) {
    console.error('registerForRaceAction failed:', error);
    return Result.err('Failed to register for race');
  }
}

// eslint-disable-next-line gridpilot-rules/server-actions-interface
export async function withdrawFromRaceAction(raceId: string, driverId: string, leagueId: string): Promise<Result<void, string>> {
  try {
    const baseUrl = getWebsiteApiBaseUrl();
    const apiClient = new RacesApiClient(
      baseUrl,
      new ConsoleErrorReporter(),
      new ConsoleLogger()
    );
    
    await apiClient.withdraw(raceId, { raceId, driverId });
    
    // Revalidate the schedule page to show updated registration status
    revalidatePath(routes.league.schedule(leagueId));
    
    return Result.ok(undefined);
  } catch (error) {
    console.error('withdrawFromRaceAction failed:', error);
    return Result.err('Failed to withdraw from race');
  }
}

// eslint-disable-next-line gridpilot-rules/server-actions-interface
export async function navigateToEditRaceAction(raceId: string, leagueId: string): Promise<void> {
  redirect(routes.league.scheduleAdmin(leagueId));
}

// eslint-disable-next-line gridpilot-rules/server-actions-interface
export async function navigateToRescheduleRaceAction(raceId: string, leagueId: string): Promise<void> {
  redirect(routes.league.scheduleAdmin(leagueId));
}

// eslint-disable-next-line gridpilot-rules/server-actions-interface
export async function navigateToRaceResultsAction(raceId: string, leagueId: string): Promise<void> {
  redirect(routes.race.results(raceId));
}
