import { defineStore } from 'pinia';
import api from '../api';

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    user: JSON.parse(localStorage.getItem('user') || '{}'),
    roles: [] as string[],
    permissions: [] as string[],
  }),
  actions: {
    async login(userInfo: any) {
      const res: any = await api.post('/login', userInfo);
      this.token = res.token;
      this.user = res.user;
      localStorage.setItem('token', res.token);
      localStorage.setItem('user', JSON.stringify(res.user));
    },
    async ssoLogin(ticket: string) {
        const res: any = await api.post('/login/sso', { ticket });
        this.token = res.token;
        this.user = res.user;
        localStorage.setItem('token', res.token);
        localStorage.setItem('user', JSON.stringify(res.user));
    },
    logout() {
      this.token = '';
      this.user = {};
      this.roles = [];
      this.permissions = [];
      localStorage.removeItem('token');
      localStorage.removeItem('user');
    },
    // We can fetch user info if needed, but for now we rely on login response and getRouters
    setPermissions(perms: string[]) {
      this.permissions = perms;
    },
    async getInfo() {
      try {
        const res: any = await api.get('/system/user/profile');
        if (res.user) {
          this.user = res.user;
          // Sync to local storage to keep it persistent on refresh (though getInfo should be called on app init ideally)
          localStorage.setItem('user', JSON.stringify(res.user));
        }
      } catch (error) {
        console.error('Failed to fetch user info', error);
      }
    }
  }
});

