import { defineStore } from 'pinia'
import { ref } from 'vue'
import { get, post, patch } from '../api/client'
import type {
  ApiResponse,
  CreateUserRequest,
  UpdateUserRequest,
  UserSummary,
} from '../types'

function apiErrorMessage(e: unknown, fallback: string): string {
  if (e && typeof e === 'object' && 'response' in e) {
    const data = (e as { response?: { data?: ApiResponse<unknown> } }).response?.data
    if (data?.error?.message) return data.error.message
  }
  if (e instanceof Error && e.message) return e.message
  return fallback
}

export const useUsersStore = defineStore('users', () => {
  const users = ref<UserSummary[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)

  async function listUsers(role?: string): Promise<void> {
    loading.value = true
    error.value = null
    try {
      const params = role ? { role } : undefined
      const response = await get<UserSummary[]>('users', params)
      if (response.success && response.data) {
        users.value = response.data
      } else {
        error.value = response.error?.message ?? 'Failed to load users'
      }
    } catch (e: unknown) {
      error.value = apiErrorMessage(e, 'Failed to load users')
    } finally {
      loading.value = false
    }
  }

  async function createUser(body: CreateUserRequest): Promise<UserSummary> {
    try {
      const response = await post<UserSummary>('users', body)
      if (!response.success || !response.data) {
        throw new Error(response.error?.message ?? 'Failed to create user')
      }
      return response.data
    } catch (e: unknown) {
      throw new Error(apiErrorMessage(e, 'Failed to create user'))
    }
  }

  async function updateUser(id: string, body: UpdateUserRequest): Promise<UserSummary> {
    try {
      const response = await patch<UserSummary>(`users/${id}`, body)
      if (!response.success || !response.data) {
        throw new Error(response.error?.message ?? 'Failed to update user')
      }
      return response.data
    } catch (e: unknown) {
      throw new Error(apiErrorMessage(e, 'Failed to update user'))
    }
  }

  async function resetPassword(id: string, newPassword: string): Promise<void> {
    try {
      const response = await post<void>(`users/${id}/reset-password`, { newPassword })
      // 204 No Content may yield an empty body
      if (response && typeof response === 'object' && 'success' in response && !response.success) {
        throw new Error(
          (response as ApiResponse<void>).error?.message ?? 'Failed to reset password',
        )
      }
    } catch (e: unknown) {
      throw new Error(apiErrorMessage(e, 'Failed to reset password'))
    }
  }

  return {
    users,
    loading,
    error,
    listUsers,
    createUser,
    updateUser,
    resetPassword,
  }
})
