// ignore_for_file: public_member_api_docs, sort_constructors_first
// Copyright (C) 2023 WYATT GROUP
// Please see the AUTHORS file for details.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

import 'dart:async';

import 'package:wyatt_architecture/wyatt_architecture.dart';
import 'package:wyatt_type_utils/wyatt_type_utils.dart';

/// {@template custom_routine}
/// A custom routine that can be used to call a routine and
/// attach custom logic to it.
/// {@endtemplate}
class CustomRoutine<R, Data> {
  /// {@macro custom_routine}
  const CustomRoutine({
    required this.routine,
    required this.attachedLogic,
    required this.onError,
    required this.onSuccess,
  });

  /// The routine to be called
  final FutureOr<Result<R, AppException>> Function() routine;

  /// The custom logic to be attached to the routine
  final FutureOr<Result<Data?, AppException>> Function(
    Result<R, AppException> routineResult,
  ) attachedLogic;

  /// The callback to be called when an error occurs
  final void Function(AppException exception) onError;

  /// The callback to be called when no error occurs
  final void Function(R result, Data? data) onSuccess;

  /// Calls the routine and calls the custom attached logic
  FutureOr<void> call() async {
    final result = await routine.call();

    // Call custom logic
    final customRoutineResult = await attachedLogic.call(result);

    // Check for errors
    if (result.isErr) {
      onError.call(result.err!);

      return;
    }
    if (customRoutineResult.isErr) {
      onError.call(customRoutineResult.err!);

      return;
    }

    // If no error
    return onSuccess.call(result.ok as R, customRoutineResult.ok);
  }
}
