export interface Me {
  id: number
  email: string
  name: string
  roles: string[]
  mustChangePassword: boolean
  avatarUrl: string | null
  color: string | null
}

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null as Me | null
  }),
  getters: {
    isAuthenticated: (state) => !!state.user,
    isAdmin: (state) => !!state.user?.roles.includes('ROLE_ADMIN')
  },
  actions: {
    async login(email: string, password: string, altcha: string) {
      const { request, token } = useApi()
      const res = await request<{ token: string }>('/api/login', {
        method: 'POST',
        body: { email, password, altcha }
      })
      token.value = res.token
      await nextTick()
      await this.fetchMe()
    },
    async fetchMe() {
      const { request } = useApi()
      this.user = await request<Me>('/api/me')
    },
    async updateProfile(payload: Partial<{ name: string; email: string; color: string }>) {
      const { request } = useApi()
      this.user = await request<Me>('/api/me', { method: 'PUT', body: payload })
      return this.user
    },
    async uploadAvatar(file: File) {
      const { request } = useApi()
      const body = new FormData()
      body.append('file', file)
      this.user = await request<Me>('/api/me/avatar', { method: 'POST', body })
      return this.user
    },
    async changePassword(currentPassword: string, newPassword: string) {
      const { request } = useApi()
      await request('/api/me/change-password', { method: 'POST', body: { currentPassword, newPassword } })
      if (this.user) this.user.mustChangePassword = false
    },
    async forgotPassword(email: string, altcha: string) {
      const { request } = useApi()
      return request<{ message: string }>('/api/forgot-password', { method: 'POST', body: { email, altcha } })
    },
    async resetPassword(token: string, newPassword: string) {
      const { request } = useApi()
      await request('/api/reset-password', { method: 'POST', body: { token, newPassword } })
    },
    logout() {
      const { token } = useApi()
      token.value = null
      this.user = null
      navigateTo('/login')
    }
  }
})
