import type { ITeamMembershipRepository } from '../../domain/repositories/ITeamMembershipRepository';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { Logger } from '@core/shared/application';
import type { UseCaseOutputPort } from '@core/shared/application/UseCaseOutputPort';

export type GetTeamMembershipInput = {
  teamId: string;
  driverId: string;
};

export type GetTeamMembership = {
  role: 'owner' | 'manager' | 'member';
  joinedAt: string;
  isActive: boolean;
};

export type GetTeamMembershipResult = {
  membership: GetTeamMembership | null;
};

export type GetTeamMembershipErrorCode = 'REPOSITORY_ERROR';

/**
 * Use Case for retrieving a driver's membership in a team.
 */
export class GetTeamMembershipUseCase {
  constructor(
    private readonly membershipRepository: ITeamMembershipRepository,
    private readonly logger: Logger,
    private readonly output: UseCaseOutputPort<GetTeamMembershipResult>,
  ) {}

  async execute(
    input: GetTeamMembershipInput,
  ): Promise<Result<void, ApplicationErrorCode<GetTeamMembershipErrorCode, { message: string }>>> {
    this.logger.debug(`Executing GetTeamMembershipUseCase for teamId: ${input.teamId}, driverId: ${input.driverId}`);

    try {
      const membership = await this.membershipRepository.getMembership(input.teamId, input.driverId);

      if (!membership) {
        this.logger.debug(`No membership found for teamId: ${input.teamId}, driverId: ${input.driverId}`);

        this.output.present({ membership: null });

        return Result.ok(undefined);
      }

      const presentableMembership: GetTeamMembership = {
        role: membership.role === 'driver' ? 'member' : (membership.role as 'owner' | 'manager' | 'member'),
        joinedAt: membership.joinedAt.toISOString(),
        isActive: membership.status === 'active',
      };

      this.output.present({ membership: presentableMembership });

      this.logger.info(`Successfully retrieved membership for teamId: ${input.teamId}, driverId: ${input.driverId}`);

      return Result.ok(undefined);
    } catch (err) {
      const error = err as { message?: string } | undefined;

      this.logger.error(
        `Error in GetTeamMembershipUseCase for teamId: ${input.teamId}, driverId: ${input.driverId}`,
        err as Error,
      );

      return Result.err({
        code: 'REPOSITORY_ERROR',
        details: {
          message: error?.message ?? 'Failed to retrieve team membership',
        },
      });
    }
  }
}