import type { StateCreator } from "zustand";
import type { AppState, AuthMode, SessionScope } from "../types";
import {
    ACCESS_TOKEN_KEY,
    REFRESH_TOKEN_KEY,
    SESSION_SCOPE_KEY,
    USER_KEY,
    readSessionAccess,
    readSessionRefresh,
    readSessionScope,
    readSessionUser,
} from "../helpers";

export type AuthSlice = Pick<
    AppState,
    "authMode" | "accessToken" | "refreshToken" | "user" | "sessionScope"
    | "setAuth" | "setSessionScope" | "clearAuth"
>;

const initialAuthMode: AuthMode = import.meta.env.DEV ? "dev" : "prod";

// 跨重启的持久化：桌面由 Go 侧（session 文件 + 启动注入 window.__CDROP_BOOT__）负责
// （wails:// scheme 下 WebView 存储不存活）；浏览器由服务端 HttpOnly session cookie
// 负责（开机 bootstrapAuth 静默续期，见 features/auth/auth.ts）。sessionStorage 仅
// 用于浏览器同 tab 刷新存活。refresh_token 永不进 JS——只在服务端 / Go 进程。
export const createAuthSlice: StateCreator<AppState, [], [], AuthSlice> = (set) =>
({
    authMode: initialAuthMode,
    accessToken: readSessionAccess(),
    refreshToken: readSessionRefresh(),
    user: readSessionUser(),
    sessionScope: readSessionScope(),

    // setAuth records the session. accessToken may be null (global-SSO browser — the
    // broker cookie carries identity). refreshToken is optional: omit it to leave a
    // previously stored one untouched (e.g. a /api/me bootstrap that only confirms the
    // user); pass null to clear it, a string to replace it.
    setAuth: (a) =>
    {
        if (typeof window !== "undefined")
        {
            if (a.accessToken) { window.sessionStorage.setItem(ACCESS_TOKEN_KEY, a.accessToken); }
            else { window.sessionStorage.removeItem(ACCESS_TOKEN_KEY); }
            if (a.refreshToken !== undefined)
            {
                if (a.refreshToken) { window.sessionStorage.setItem(REFRESH_TOKEN_KEY, a.refreshToken); }
                else { window.sessionStorage.removeItem(REFRESH_TOKEN_KEY); }
            }
            window.sessionStorage.setItem(USER_KEY, JSON.stringify(a.user));
        }
        set((s) =>
        ({
            accessToken: a.accessToken,
            refreshToken: a.refreshToken !== undefined ? a.refreshToken : s.refreshToken,
            user: a.user,
        }));
    },

    // setSessionScope 由 /api/me 解析结果驱动（登录成功 / 开机水合后调用）。
    // 持久化到 sessionStorage，使同 tab 刷新沿用，不必再次往返 /api/me 才能正确
    // 隐藏受限入口。
    setSessionScope: (scope: SessionScope) =>
    {
        if (typeof window !== "undefined")
        {
            window.sessionStorage.setItem(SESSION_SCOPE_KEY, scope);
        }
        set({ sessionScope: scope });
    },

    clearAuth: () =>
    {
        if (typeof window !== "undefined")
        {
            window.sessionStorage.removeItem(ACCESS_TOKEN_KEY);
            window.sessionStorage.removeItem(REFRESH_TOKEN_KEY);
            window.sessionStorage.removeItem(USER_KEY);
            window.sessionStorage.removeItem(SESSION_SCOPE_KEY);
        }
        // scope 回 "full"：登出后下一个登录者默认完整态，再由其自己的 /api/me 校正。
        set({ accessToken: null, refreshToken: null, user: null, sessionScope: "full" });
    },
});
