import { ref } from 'vue'
import { useApi } from './useApi'

export interface AdminProfile {
  id: string
  firstName: string
  lastName: string
  email: string | null
  isActive: boolean
  hasPassword: boolean
  roles: string[]
  createdAt: string
  updatedAt: string
}

export function useAdminProfiles() {
  const { get, post, put } = useApi()
  const profiles = ref<AdminProfile[]>([])
  const loading = ref(false)

  const fetchAll = async () => {
    loading.value = true
    try {
      const result = await get<AdminProfile[]>('/admin/profiles')
      if (result.success && result.data) {
        profiles.value = result.data
      }
    } finally {
      loading.value = false
    }
  }

  const createProfile = async (data: {
    firstName: string
    lastName: string
    email?: string
    password?: string
    role?: string
  }) => {
    const result = await post<AdminProfile>('/admin/profiles', data)
    if (result.success) {
      await fetchAll()
    }
    return result
  }

  const updateRole = async (id: string, role: string) => {
    const result = await put<AdminProfile>(`/admin/profiles/${id}/role`, { role })
    if (result.success) {
      await fetchAll()
    }
    return result
  }

  const setPassword = async (id: string, password: string) => {
    const result = await put<AdminProfile>(`/admin/profiles/${id}/password`, { password })
    if (result.success) {
      await fetchAll()
    }
    return result
  }

  const deactivateProfile = async (id: string) => {
    const result = await put<AdminProfile>(`/admin/profiles/${id}/deactivate`, {})
    if (result.success) {
      await fetchAll()
    }
    return result
  }

  return {
    profiles,
    loading,
    fetchAll,
    createProfile,
    updateRole,
    setPassword,
    deactivateProfile,
  }
}
