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

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: LeagueMembershipRepository) {}

  async execute(
    params: RemoveLeagueMemberInput,
  ): Promise<Result<RemoveLeagueMemberResult, 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);

      const result: RemoveLeagueMemberResult = {
        leagueId: params.leagueId,
        memberId: params.targetDriverId,
        removedRole: membership.role.toString(),
      };

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

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