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

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('tyt_token') || '',
    userInfo: JSON.parse(localStorage.getItem('tyt_user_info') || 'null'),
  }),
  getters: {
    isLoggedIn: (state) => !!state.token,
    role: (state) => state.userInfo?.role || '',
  },
  actions: {
    setToken(token) {
      this.token = token;
      localStorage.setItem('tyt_token', token);
    },
    setUserInfo(info) {
      this.userInfo = info;
      localStorage.setItem('tyt_user_info', JSON.stringify(info));
    },
    applyLoginResponse(data) {
      if (!data?.accessToken) {
        return false;
      }

      this.setToken(data.accessToken);
      if (data.user) {
        this.setUserInfo(data.user);
      }
      return true;
    },
    async login(loginForm) {
      const payload = { ...loginForm };
      if (!payload.role) {
        delete payload.role;
      }
      if (!payload.hospitalId) {
        delete payload.hospitalId;
      }
      const data = await request.post('/auth/login', payload);
      if (data?.needSelect) {
        return {
          needSelect: true,
          loginTicket: data.loginTicket,
          accounts: data.accounts || [],
        };
      }

      const success = this.applyLoginResponse(data);
      return {
        needSelect: false,
        success,
      };
    },
    async confirmLogin(loginTicket, userId) {
      const data = await request.post('/auth/login/confirm', {
        loginTicket,
        userId,
      });

      const success = this.applyLoginResponse(data);
      return {
        success,
      };
    },
    async fetchUserInfo() {
      try {
        const userInfo = await request.get('/auth/me');
        this.setUserInfo(userInfo);
        return userInfo;
      } catch (error) {
        this.logout();
        throw error;
      }
    },
    logout() {
      this.token = '';
      this.userInfo = null;
      localStorage.removeItem('tyt_token');
      localStorage.removeItem('tyt_user_info');
    },
  },
});
