import { fromPromise } from "xstate";

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

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

export interface InitData {
  user: UserView | null;
  avatarUrl: string | null;
  snapshot: UserEntitlementSnapshotData | null;
}

export const userInitActor = fromPromise<InitData>(async () => {
  const userStorage = UserStorage.getInstance();
  const [userResult, avatarResult, snapshotResult] = await Promise.all([
    userStorage.getUser(),
    userStorage.getAvatarUrl(),
    userStorage.getEntitlementSnapshot(),
  ]);

  const snapshot =
    Result.isOk(snapshotResult) && snapshotResult.data
      ? snapshotResult.data
      : null;
  const user =
    Result.isOk(userResult) && userResult.data
      ? applyEntitlementSnapshotToView(toView(userResult.data), snapshot)
      : null;
  const avatarUrl =
    Result.isOk(avatarResult) &&
    avatarResult.data &&
    avatarResult.data.length > 0
      ? avatarResult.data
      : null;

  return { user, avatarUrl, snapshot };
});

export const userLogoutActor = fromPromise<void>(async () => {
  const result = await getAuthRepository().logout();
  if (Result.isErr(result)) throw result.error;
});
