import { defineStore } from 'pinia'
import { getToken, removeToken, setToken, changeLoalName } from './helper'
import { fetchSession, fetchPhoneLogin } from '@/api'
import { Response } from '@/utils/request'
import { useUserStore } from '../user'
import { useCompanyStore } from '../company'

interface SessionResponse {
    auth: boolean
    model: 'ChatGPTAPI' | 'ChatGPTUnofficialProxyAPI'
}

export interface AuthState {
    token: string | undefined
    session: SessionResponse | null
    user: Chat.User | null
}

export const useAuthStore = defineStore('auth-store', {
    state: (): AuthState => ({
        token: getToken(),
        session: null,
        user: null
    }),

    getters: {
        isChatGPTAPI(state): boolean {
            return state.session?.model === 'ChatGPTAPI'
        }
    },

    actions: {
        async getSession() {
            try {
                const { data } = await fetchSession<Response<SessionResponse>>()
                this.session = { ...data }
                return Promise.resolve(data)
            } catch (error) {
                return Promise.reject(error)
            }
        },

        setToken(token: string) {
            this.token = token
            setToken(token)
        },

        removeToken() {
            this.token = undefined
            removeToken()
        },

        async phoneLogin(phone: string | number, code: string | number, invitor?: string | number) {
            const data = await fetchPhoneLogin<any>(phone, code, invitor)
           
            if (import.meta.env.VITE_ORG_MODE === 'true') {
                const companyStore = useCompanyStore()
                if (data.user.orgId !== companyStore.company.id) {
                    throw new Error('该账号暂无权限登录')
                }
            }

            this.setToken(data.access_token)
            const userStore = useUserStore()
            await userStore.fetch()
        }
    }
})
