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

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, void, LogoutErrorCode> {
  private readonly sessionPort: IdentitySessionPort;

  constructor(
    sessionPort: IdentitySessionPort,
    private readonly logger: Logger,
    private readonly output: UseCaseOutputPort<LogoutResult>,
  ) {
    this.sessionPort = sessionPort;
  }

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

      const result: LogoutResult = { success: true };
      this.output.present(result);

      return Result.ok(undefined);
    } 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);
    }
  }
}