/**
 * 邀請網絡 local stub（後端 M6 前暫用 localStorage 島民表）。
 */
import {
  adminMoveInviteMember,
  applyInviteCode,
  buildInviteForest,
  getMyInviteNetwork,
  listInviteParentCandidates,
} from "../../lib/inviteNetwork";
import type { InviteRepo } from "../repos";
import { mockDelay } from "../../lib/mockAi";
import { findUserByUid, toMember } from "../../lib/tenantUsers";
import { getSession, setSession } from "./store";

function memberFromSession() {
  const s = getSession();
  if (!s?.member) return null;
  const live = findUserByUid(s.member.uid);
  if (live) return toMember(live);
  return s.member;
}

export function createMockInviteRepo(): InviteRepo {
  return {
    async getMyNetwork() {
      await mockDelay(100);
      const me = memberFromSession();
      if (!me) throw new Error("invite.err.notLoggedIn");
      return getMyInviteNetwork(me.uid);
    },
    async applyInviteCode(code) {
      await mockDelay(180);
      const me = memberFromSession();
      if (!me) throw new Error("invite.err.notLoggedIn");
      const network = applyInviteCode(me.uid, code);
      // 同步 session.member.parent_uid
      const live = findUserByUid(me.uid);
      const sess = getSession();
      if (live && sess) {
        setSession({ ...sess, member: toMember(live) });
      }
      return network;
    },
    async getTree() {
      await mockDelay(120);
      const me = memberFromSession();
      if (!me?.roles.includes("admin")) throw new Error("invite.err.needAdmin");
      return buildInviteForest();
    },
    async moveMember(uid, newParentUid) {
      await mockDelay(200);
      const me = memberFromSession();
      if (!me?.roles.includes("admin")) throw new Error("invite.err.needAdmin");
      return adminMoveInviteMember(true, uid, newParentUid);
    },
    async listParentCandidates(excludeSubtreeRootUid) {
      await mockDelay(80);
      const me = memberFromSession();
      if (!me?.roles.includes("admin")) throw new Error("invite.err.needAdmin");
      return listInviteParentCandidates(excludeSubtreeRootUid);
    },
  };
}
