/**
 * Application Use Case: GetMembershipFeesUseCase
 *
 * Retrieves membership fees and member payments.
 */

import type { UseCase } from '@core/shared/application/UseCase';
import { Result } from '@core/shared/domain/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { MemberPayment } from '../../domain/entities/MemberPayment';
import type { MembershipFee } from '../../domain/entities/MembershipFee';
import type { MemberPaymentRepository, MembershipFeeRepository } from '../../domain/repositories/MembershipFeeRepository';

export type GetMembershipFeesErrorCode = 'INVALID_INPUT';

export interface GetMembershipFeesInput {
  leagueId: string;
  driverId?: string;
}

export interface GetMembershipFeesResult {
  fee: MembershipFee | null;
  payments: MemberPayment[];
}

export class GetMembershipFeesUseCase
  implements UseCase<GetMembershipFeesInput, GetMembershipFeesResult, GetMembershipFeesErrorCode>
{
  constructor(
    private readonly membershipFeeRepository: MembershipFeeRepository,
    private readonly memberPaymentRepository: MemberPaymentRepository,
  ) {}

  async execute(input: GetMembershipFeesInput): Promise<Result<GetMembershipFeesResult, ApplicationErrorCode<GetMembershipFeesErrorCode>>> {
    const { leagueId, driverId } = input;

    if (!leagueId) {
      return Result.err({ code: 'INVALID_INPUT' as const });
    }

    const fee = await this.membershipFeeRepository.findByLeagueId(leagueId);

    let payments: MemberPayment[] = [];
    if (driverId && fee) {
      payments = await this.memberPaymentRepository.findByLeagueIdAndDriverId(leagueId, driverId, this.membershipFeeRepository);
    }

    return Result.ok({ fee, payments });
  }
}