import { injectable, unmanaged } from 'inversify';
import { TeamsApiClient } from '@/lib/api/teams/TeamsApiClient';
import { TeamJoinRequestViewModel } from '@/lib/view-models/TeamJoinRequestViewModel';
import { Result } from '@/lib/contracts/Result';
import { DomainError, Service } from '@/lib/contracts/services/Service';
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
import { EnhancedErrorReporter } from '@/lib/infrastructure/EnhancedErrorReporter';
import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';
import { isProductionEnvironment } from '@/lib/config/env';

/**
 * Team Join Service - ViewModels
 *
 * Returns ViewModels for team join requests.
 * Handles presentation logic for join request management.
 */
@injectable()
export class TeamJoinService implements Service {
  private apiClient: TeamsApiClient;

  constructor(@unmanaged() apiClient?: TeamsApiClient) {
    if (apiClient) {
      this.apiClient = apiClient;
    } else {
      const baseUrl = getWebsiteApiBaseUrl();
      const logger = new ConsoleLogger();
      const errorReporter = new EnhancedErrorReporter(logger, {
        showUserNotifications: true,
        logToConsole: true,
        reportToExternal: isProductionEnvironment(),
      });
      this.apiClient = new TeamsApiClient(baseUrl, errorReporter, logger);
    }
  }

  async getJoinRequests(teamId: string, currentDriverId: string, isOwner: boolean): Promise<Result<TeamJoinRequestViewModel[], DomainError>> {
    try {
      const result = await this.apiClient.getJoinRequests(teamId);
      const requests = (result as any).requests || result;
      const viewModels = requests.map((request: any) => 
        new TeamJoinRequestViewModel(request, currentDriverId, isOwner)
      );
      return Result.ok(viewModels);
    } catch (error: any) {
      return Result.err({ type: 'serverError', message: error.message || 'Failed to fetch join requests' });
    }
  }

  async approveJoinRequest(): Promise<Result<void, DomainError>> {
    return Result.err({ type: 'notImplemented', message: 'Not implemented: API endpoint for approving join requests' });
  }

  async rejectJoinRequest(): Promise<Result<void, DomainError>> {
    return Result.err({ type: 'notImplemented', message: 'Not implemented: API endpoint for rejecting join requests' });
  }
}
