/**
 * User 状态机（XState v5）
 */
import { setup, assign } from "xstate";

import { UserState, initialState } from "./user-state";
import type { UserEvent } from "./user-events";
import {
  userInitActor,
  userFetchActor,
  userLogoutActor,
} from "./user-machine.actors";

// 重新导出 State / Event 类型，保持 machine 文件的公共 API 不变
export type { UserState } from "./user-state";
export { initialState } from "./user-state";
export type { UserEvent } from "./user-events";

// ============================================================
// Machine
// ============================================================
export const userMachine = setup({
  types: {
    context: {} as UserState,
    events: {} as UserEvent,
  },
  actors: {
    userInit: userInitActor,
    userFetch: userFetchActor,
    userLogout: userLogoutActor,
  },
  actions: {
    updateUser: assign(({ event }) => {
      if (event.type !== "UserUpdate") return {};
      return { currentUser: event.user };
    }),

    updateUsername: assign(({ context, event }) => {
      if (event.type !== "UserUpdateUsername" || !context.currentUser) return {};
      return {
        currentUser: { ...context.currentUser, username: event.username },
      };
    }),

    updatePronouns: assign(({ event }) => {
      if (event.type !== "UserUpdatePronouns") return {};
      return { pronouns: event.pronouns };
    }),

    clearUser: assign(() => ({
      currentUser: null,
      avatarUrl: null,
    })),
  },
}).createMachine({
  id: "user",
  initial: "idle",
  context: initialState,
  states: {
    idle: {
      on: {
        UserInit: "initializing",
        UserFetch: "fetching",
        UserUpdate: {
          actions: "updateUser",
        },
        UserUpdateUsername: {
          actions: "updateUsername",
        },
        UserUpdatePronouns: {
          actions: "updatePronouns",
        },
        UserClearLocal: {
          actions: "clearUser",
        },
        UserLogout: "loggingOut",
        UserDeleteChatHistory: {},
        UserDeleteAccount: {},
      },
    },

    initializing: {
      invoke: {
        src: "userInit",
        onDone: {
          target: "idle",
          actions: assign(({ event }) => ({
            currentUser: event.output.user,
            avatarUrl: event.output.avatarUrl,
          })),
        },
        onError: {
          target: "idle",
        },
      },
    },

    fetching: {
      invoke: {
        src: "userFetch",
        onDone: {
          target: "idle",
          actions: assign(({ event }) => ({
            currentUser: event.output,
          })),
        },
        onError: {
          target: "idle",
          actions: assign({ isLoading: false }),
        },
      },
      entry: assign({ isLoading: true }),
    },

    loggingOut: {
      invoke: {
        src: "userLogout",
        onDone: {
          target: "idle",
          actions: "clearUser",
        },
        onError: {
          target: "idle",
          actions: "clearUser",
        },
      },
    },
  },
});

export type UserMachine = typeof userMachine;
