import type { ILeagueMembershipRepository } from '../../domain/repositories/ILeagueMembershipRepository';
import { Result } from '@core/shared/application/Result';
import { UseCaseOutputPort } from '@core/shared/application';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import { LeagueMembership } from '../../domain/entities/LeagueMembership';

export interface RemoveLeagueMemberInput {
  leagueId: string;
  targetDriverId: string;
}

export interface RemoveLeagueMemberResult {
  leagueId: string;
  memberId: string;
  removedRole: string;
}

export type RemoveLeagueMemberErrorCode =
  | 'MEMBERSHIP_NOT_FOUND'
  | 'CANNOT_REMOVE_LAST_OWNER'
  | 'REPOSITORY_ERROR';

export class RemoveLeagueMemberUseCase {
  constructor(
    private readonly leagueMembershipRepository: ILeagueMembershipRepository,
    private readonly output: UseCaseOutputPort<RemoveLeagueMemberResult>,
  ) {}

  async execute(
    params: RemoveLeagueMemberInput,
  ): Promise<Result<void, ApplicationErrorCode<RemoveLeagueMemberErrorCode, { message: string }>>> {
    try {
      const membership = await this.leagueMembershipRepository.getMembership(
        params.leagueId,
        params.targetDriverId,
      );

      if (!membership) {
        return Result.err({
          code: 'MEMBERSHIP_NOT_FOUND',
          details: { message: 'Membership not found for given league and driver' },
        });
      }

      if (membership.role.toString() === 'owner') {
        const members = await this.leagueMembershipRepository.getLeagueMembers(params.leagueId);
        const ownerCount = members.filter(m => m.role.toString() === 'owner').length;

        if (ownerCount <= 1) {
          return Result.err({
            code: 'CANNOT_REMOVE_LAST_OWNER',
            details: { message: 'Cannot remove the last owner' },
          });
        }
      }

      const updatedMembership = LeagueMembership.create({
        id: membership.id,
        leagueId: membership.leagueId.toString(),
        driverId: membership.driverId.toString(),
        role: membership.role.toString(),
        status: 'inactive',
        joinedAt: membership.joinedAt.toDate(),
      });

      await this.leagueMembershipRepository.saveMembership(updatedMembership);

      this.output.present({
        leagueId: params.leagueId,
        memberId: params.targetDriverId,
        removedRole: membership.role.toString(),
      });

      return Result.ok(undefined);
    } catch (error) {
      const err = error as Error;

      return Result.err({
        code: 'REPOSITORY_ERROR',
        details: { message: err?.message ?? 'Failed to remove league member' },
      });
    }
  }
}