import * as SecureStore from 'expo-secure-store';
import { create } from 'zustand';

type UserSession = {
  username: string;
  displayName: string;
  roleCodes: string[];
};

type SessionState = {
  user: UserSession | null;
  restore: () => Promise<void>;
  signInAsDemoUser: () => Promise<void>;
  signOut: () => Promise<void>;
};

const storageKey = 'x-financial-mobile-session';

const demoSession: UserSession = {
  username: 'zhangsan',
  displayName: '张三',
  roleCodes: ['employee'],
};

export const useSessionStore = create<SessionState>((set) => ({
  user: demoSession,
  async restore() {
    const raw = await SecureStore.getItemAsync(storageKey);
    set({ user: raw ? (JSON.parse(raw) as UserSession) : demoSession });
  },
  async signInAsDemoUser() {
    await SecureStore.setItemAsync(storageKey, JSON.stringify(demoSession));
    set({ user: demoSession });
  },
  async signOut() {
    await SecureStore.deleteItemAsync(storageKey);
    set({ user: null });
  },
}));

export function buildAuthHeaders(user: UserSession | null) {
  if (!user) {
    return {};
  }
  return {
    'X-Auth-Username': user.username,
    'X-Auth-Name': user.displayName,
    'X-Auth-Role-Codes': user.roleCodes.join(','),
    'X-Auth-Is-Admin': 'false',
  };
}
