import { fromPromise } from "xstate";

import type { UserView } from "@/data/dto/user";
import { getUserRepository } from "@/data/repositories/user_repository";
import type { UserEntitlementSnapshotData } from "@/data/schemas/user";
import { UserStorage } from "@/data/storage/user/user_storage";
import { Result } from "@/utils/result";

import {
  applyEntitlementSnapshotToView,
  toEntitlementSnapshot,
  toView,
} from "../../helper/view";

export interface UserFetchData {
  user: UserView | null;
  snapshot: UserEntitlementSnapshotData | null;
}

export const userFetchActor = fromPromise<UserFetchData>(async () => {
  const userRepo = getUserRepository();
  const userStorage = UserStorage.getInstance();
  const [userResult, entitlementsResult] = await Promise.all([
    userRepo.getCurrentUser(),
    userRepo.getEntitlements(),
  ]);

  const snapshot = Result.isOk(entitlementsResult)
    ? toEntitlementSnapshot({
        isVip: entitlementsResult.data.isVip,
        creditBalance: entitlementsResult.data.creditBalance,
      })
    : null;
  if (snapshot) await userStorage.setEntitlementSnapshot(snapshot);

  if (Result.isErr(userResult)) return { user: null, snapshot };

  const view = applyEntitlementSnapshotToView(
    toView(userResult.data.toJson()),
    snapshot,
  );
  await userStorage.setUser(userResult.data.toJson());
  return { user: view, snapshot };
});
