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';
import type { MembershipRole } from '@/lib/types/MembershipRole';

/**
 * RosterAdminMutation
 * 
 * Framework-agnostic mutation for roster administration operations.
 * Can be called from Server Actions or other contexts.
 */
export class RosterAdminMutation {
  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 approveJoinRequest(leagueId: string, joinRequestId: string): Promise<Result<void, string>> {
    try {
      await this.service.approveJoinRequest(leagueId, joinRequestId);
      return Result.ok(undefined);
    } catch (error) {
      console.error('approveJoinRequest failed:', error);
      return Result.err('Failed to approve join request');
    }
  }

  async rejectJoinRequest(leagueId: string, joinRequestId: string): Promise<Result<void, string>> {
    try {
      await this.service.rejectJoinRequest(leagueId, joinRequestId);
      return Result.ok(undefined);
    } catch (error) {
      console.error('rejectJoinRequest failed:', error);
      return Result.err('Failed to reject join request');
    }
  }

  async updateMemberRole(leagueId: string, driverId: string, role: MembershipRole): Promise<Result<void, string>> {
    try {
      await this.service.updateMemberRole(leagueId, driverId, role);
      return Result.ok(undefined);
    } catch (error) {
      console.error('updateMemberRole failed:', error);
      return Result.err('Failed to update member role');
    }
  }

  async removeMember(leagueId: string, driverId: string): Promise<Result<void, string>> {
    try {
      await this.service.removeMember(leagueId, driverId);
      return Result.ok(undefined);
    } catch (error) {
      console.error('removeMember failed:', error);
      return Result.err('Failed to remove member');
    }
  }
}