import type { UseCase } from '@core/shared/application/UseCase';
import type { Logger } from '@core/shared/domain/Logger';
import { Result } from '@core/shared/domain/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { IdentitySessionPort } from '../ports/IdentitySessionPort';

export type LogoutInput = {};

export type LogoutResult = {
  success: boolean;
};

export type LogoutErrorCode = 'REPOSITORY_ERROR';

export type LogoutApplicationError = ApplicationErrorCode<LogoutErrorCode, { message: string }>;

export class LogoutUseCase implements UseCase<LogoutInput, LogoutResult, LogoutErrorCode> {
  private readonly sessionPort: IdentitySessionPort;

  constructor(
    sessionPort: IdentitySessionPort,
    private readonly logger: Logger,
  ) {
    this.sessionPort = sessionPort;
  }

  async execute(): Promise<Result<LogoutResult, LogoutApplicationError>> {
    try {
      await this.sessionPort.clearSession();

      const result: LogoutResult = { success: true };

      return Result.ok(result);
    } catch (error) {
      const message =
        error instanceof Error && error.message
          ? error.message
          : 'Failed to execute LogoutUseCase';

      this.logger.error(
        'LogoutUseCase.execute failed',
        error instanceof Error ? error : undefined,
        {},
      );

      return Result.err({
        code: 'REPOSITORY_ERROR',
        details: { message },
      } as LogoutApplicationError);
    }
  }
}