import { Result } from '@core/shared/domain/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { TeamMembershipRepository } from '../../domain/repositories/TeamMembershipRepository';
import type {
    TeamJoinRequest,
    TeamMembership,
} from '../../domain/types/TeamMembership';

export type ApproveTeamJoinRequestInput = {
  teamId: string;
  requestId: string;
};

export type ApproveTeamJoinRequestResult = {
  membership: TeamMembership;
};

export type ApproveTeamJoinRequestErrorCode =
  | 'TEAM_NOT_FOUND'
  | 'REQUEST_NOT_FOUND'
  | 'NOT_AUTHORIZED'
  | 'REPOSITORY_ERROR';

export class ApproveTeamJoinRequestUseCase {
  constructor(
    private readonly membershipRepository: TeamMembershipRepository,
  ) {}

  async execute(command: ApproveTeamJoinRequestInput): Promise<
    Result<ApproveTeamJoinRequestResult, ApplicationErrorCode<ApproveTeamJoinRequestErrorCode>>
  > {
    const { teamId, requestId } = command;

    try {
      const allRequests: TeamJoinRequest[] = await this.membershipRepository.getJoinRequests(teamId);
      const request = allRequests.find((r) => r.id === requestId);

      if (!request) {
        return Result.err({ code: 'REQUEST_NOT_FOUND' });
      }

      const membership: TeamMembership = {
        teamId: request.teamId,
        driverId: request.driverId,
        role: 'driver',
        status: 'active',
        joinedAt: new Date(),
      };

      await this.membershipRepository.saveMembership(membership);
      await this.membershipRepository.removeJoinRequest(requestId);

      const result: ApproveTeamJoinRequestResult = {
        membership,
      };

      return Result.ok(result);
    } catch (error) {
      return Result.err({
        code: 'REPOSITORY_ERROR',
        details: {
          message: error instanceof Error ? error.message : String(error),
        },
      });
    }
  }
}
