import { defineStore } from 'pinia';
import { authApi } from '../api/modules';
import { router } from '../router';

interface LoginResult {
  accessToken: string;
  refreshToken: string;
  user: {
    id: string;
    username: string;
    name: string;
    tenant: {
      id: string;
      code: string;
      name: string;
    };
    roles: string[];
    permissions: string[];
    regionIds: string[];
  };
}

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: JSON.parse(localStorage.getItem('user') || 'null') as LoginResult['user'] | null,
  }),
  getters: {
    permissions: (state) => state.user?.permissions ?? [],
  },
  actions: {
    async login(tenantCode: string, username: string, password: string) {
      const result = (await authApi.login({ tenantCode, username, password })) as unknown as LoginResult;
      localStorage.setItem('accessToken', result.accessToken);
      localStorage.setItem('refreshToken', result.refreshToken);
      localStorage.setItem('user', JSON.stringify(result.user));
      this.user = result.user;
    },
    logout() {
      localStorage.removeItem('accessToken');
      localStorage.removeItem('refreshToken');
      localStorage.removeItem('user');
      this.user = null;
      if (router.currentRoute.value.path !== '/login') {
        void router.push('/login');
      }
    },
  },
});
