/**
 * DriverTeamPresenter - Pure data transformer
 * Transforms API response to view model without DI dependencies.
 */

import { apiClient, type DriverTeamViewModel as ApiDriverTeamViewModel } from '@/lib/apiClient';

export interface DriverTeamMembershipViewModel {
  role: string;
  joinedAt: string;
  isActive: boolean;
}

export interface DriverTeamInfoViewModel {
  id: string;
  name: string;
  tag?: string | undefined;
  description?: string | undefined;
  ownerId: string;
  leagues?: string[] | undefined;
}

export interface DriverTeamViewModel {
  team: DriverTeamInfoViewModel;
  membership: DriverTeamMembershipViewModel;
  isOwner: boolean;
  canManage: boolean;
}

export interface IDriverTeamPresenter {
  reset(): void;
  getViewModel(): DriverTeamViewModel | null;
}

/**
 * Transform API response to view model
 */
function transformApiResponse(apiResponse: ApiDriverTeamViewModel): DriverTeamViewModel {
  const isOwner = false; // Would need team owner info from API
  const canManage = apiResponse.role === 'owner' || apiResponse.role === 'manager';

  return {
    team: {
      id: apiResponse.teamId,
      name: apiResponse.teamName,
      ownerId: '', // Would need from API
    },
    membership: {
      role: apiResponse.role === 'driver' ? 'member' : apiResponse.role,
      joinedAt: new Date(apiResponse.joinedAt).toISOString(),
      isActive: true,
    },
    isOwner,
    canManage,
  };
}

export class DriverTeamPresenter implements IDriverTeamPresenter {
  private viewModel: DriverTeamViewModel | null = null;

  reset(): void {
    this.viewModel = null;
  }

  async fetchAndPresent(driverId: string): Promise<void> {
    const apiResponse = await apiClient.teams.getDriverTeam(driverId);
    if (apiResponse) {
      this.viewModel = transformApiResponse(apiResponse);
    } else {
      this.viewModel = null;
    }
  }

  getViewModel(): DriverTeamViewModel | null {
    return this.viewModel;
  }
}

/**
 * Convenience function to fetch and transform driver's team
 */
export async function fetchDriverTeam(driverId: string): Promise<DriverTeamViewModel | null> {
  const apiResponse = await apiClient.teams.getDriverTeam(driverId);
  if (!apiResponse) {
    return null;
  }
  return transformApiResponse(apiResponse);
}