import Failure from "core/failure";
import { Service } from "services/domain/serviceEntity";
import { ServiceSession } from "subscriptions/domain/sessionEntity";
import { SubscriptionsStore } from "subscriptions/domain/subscriptionsStore";

type ForkToServiceStore = Pick<SubscriptionsStore, "forkTo">;

const forkToServiceUseCase = (
  store: ForkToServiceStore,
  id: Service["id"]
): Promise<ServiceSession> => {
  return store.forkTo(id).catch((reason) => {
    if (
      reason instanceof Failure &&
      reason.status === 403 &&
      reason.meta?.data.data.redirect_url
    ) {
      window.open(reason.meta?.data.data.redirect_url);
    }
    throw reason;
  });
};

export { forkToServiceUseCase };
