import { injectable, unmanaged } from 'inversify';
import { TeamsApiClient } from '@/lib/api/teams/TeamsApiClient';
import type { TeamListItemDTO } from '@/lib/types/generated/TeamListItemDTO';
import type { CreateTeamInputDTO } from '@/lib/types/generated/CreateTeamInputDTO';
import type { CreateTeamOutputDTO } from '@/lib/types/generated/CreateTeamOutputDTO';
import type { UpdateTeamInputDTO } from '@/lib/types/generated/UpdateTeamInputDTO';
import type { UpdateTeamOutputDTO } from '@/lib/types/generated/UpdateTeamOutputDTO';
import type { GetDriverTeamOutputDTO } from '@/lib/types/generated/GetDriverTeamOutputDTO';
import type { GetTeamMembershipOutputDTO } from '@/lib/types/generated/GetTeamMembershipOutputDTO';
import type { GetTeamJoinRequestsOutputDTO } from '@/lib/types/generated/GetTeamJoinRequestsOutputDTO';
import type { GetTeamDetailsOutputDTO } from '@/lib/types/generated/GetTeamDetailsOutputDTO';
import { TeamMemberViewModel } from '@/lib/view-models/TeamMemberViewModel';
import { TeamSummaryViewModel } from '@/lib/view-models/TeamSummaryViewModel';
import { TeamDetailsViewModel } from '@/lib/view-models/TeamDetailsViewModel';
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 Service - DTO Only
 *
 * Returns raw API DTOs. No ViewModels or UX logic.
 * All client-side presentation logic must be handled by hooks/components.
 */
@injectable()
export class TeamService 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 getMembers(teamId: string): Promise<Result<any, DomainError>> {
    try {
      const result = await this.apiClient.getMembers(teamId);
      return Result.ok(result);
    } catch (error: unknown) {
      return Result.err({ type: 'unknown', message: (error as Error).message || 'Failed to fetch team members' });
    }
  }

  async update(teamId: string, input: UpdateTeamInputDTO): Promise<Result<UpdateTeamOutputDTO, DomainError>> {
    try {
      const result = await this.apiClient.update(teamId, input);
      return Result.ok((result as any).value || result);
    } catch (error: unknown) {
      return Result.err({ type: 'unknown', message: (error as Error).message || 'Failed to update team' });
    }
  }

  async create(input: CreateTeamInputDTO): Promise<Result<CreateTeamOutputDTO, DomainError>> {
    try {
      const result = await this.apiClient.create(input);
      return Result.ok((result as any).value || result);
    } catch (error: unknown) {
      return Result.err({ type: 'unknown', message: (error as Error).message || 'Failed to create team' });
    }
  }

  async getTeamDetails(teamId: string, _: string): Promise<Result<GetTeamDetailsOutputDTO, DomainError>> {
    try {
      const result = await this.apiClient.getDetails(teamId);
      if (!result) {
        return Result.err({ type: 'notFound', message: 'Team not found' });
      }
      return Result.ok((result as any).value || result);
    } catch (error: unknown) {
      return Result.err({ type: 'unknown', message: (error as Error).message || 'Failed to fetch team details' });
    }
  }

  async getTeamMembers(teamId: string, currentDriverId: string, ownerId: string): Promise<Result<TeamMemberViewModel[], DomainError>> {
    try {
      const result = await this.apiClient.getMembers(teamId);
      const members = (result as any).members || result;
      const viewModels = members.map((member: any) => new TeamMemberViewModel(member, currentDriverId, ownerId));
      return Result.ok(viewModels);
    } catch (error: unknown) {
      return Result.err({ type: 'unknown', message: (error as Error).message || 'Failed to fetch team members' });
    }
  }

  async getTeamJoinRequests(teamId: string): Promise<Result<any, DomainError>> {
    try {
      const result = await this.apiClient.getJoinRequests(teamId);
      return Result.ok((result as any).value || result);
    } catch (error: unknown) {
      return Result.err({ type: 'unknown', message: (error as Error).message || 'Failed to fetch join requests' });
    }
  }

  async createTeam(input: CreateTeamInputDTO): Promise<Result<any, DomainError>> {
    return this.create(input);
  }

  async updateTeam(teamId: string, input: UpdateTeamInputDTO): Promise<Result<any, DomainError>> {
    return this.update(teamId, input);
  }

  async getDriverTeam(driverId: string): Promise<Result<any, DomainError>> {
    try {
      const result = await this.apiClient.getDriverTeam(driverId);
      if (!result) return Result.ok(null);
      const data = (result as any).value || result;
      if (!data.team) return Result.ok(null);
      return Result.ok({
        teamId: data.team.id,
        teamName: data.team.name,
        role: data.membership?.role,
      });
    } catch (error: unknown) {
      return Result.err({ type: 'unknown', message: (error as Error).message || 'Failed to fetch driver team' });
    }
  }

  async getAllTeams(): Promise<Result<TeamListItemDTO[], DomainError>> {
    try {
      const result = await this.apiClient.getAll();
      const teams = (result as any).teams || result;
      return Result.ok(teams);
    } catch (error: unknown) {
      return Result.err({ type: 'unknown', message: (error as Error).message || 'Failed to fetch all teams' });
    }
  }

  async getMembership(teamId: string, driverId: string): Promise<Result<GetTeamMembershipOutputDTO | null, DomainError>> {
    try {
      const result = await this.apiClient.getMembership(teamId, driverId);
      return Result.ok(result);
    } catch (error: unknown) {
      return Result.err({ type: 'unknown', message: (error as Error).message || 'Failed to fetch team membership' });
    }
  }
}