import { api } from '@/utils/request'
import type { PaginatedData } from '@/types/api'

export interface UserRecord {
  id: number
  username: string
  email: string
  status: number
  role_id: number
  role?: { id: number; name: string }
  ext: Record<string, unknown> | null
  created_at: string
  updated_at: string
  api_key_enabled: boolean
}

export interface UserFilters {
  username: string
  email: string
  status: number | undefined
  role_id: number | undefined
}

export interface ScopeRecord {
  scope_type: 'company' | 'platform' | 'store'
  scope_id: number
  name?: string | null
}

export interface UserDataScope {
  user_id: number
  role: string | null
  scopes: ScopeRecord[]
  resolved_store_ids: number[]
}

export const useUserManageStore = defineStore('user-manage', () => {
  const users = ref<UserRecord[]>([])
  const loading = ref(false)
  const pagination = reactive({
    page: 1,
    per_page: 10,
    total: 0,
  })
  const filters = reactive<UserFilters>({
    username: '',
    email: '',
    status: undefined,
    role_id: undefined,
  })

  async function fetchUsers() {
    loading.value = true
    try {
      const data = await api.get<PaginatedData<UserRecord>>('/api/v1/users', {
        page: pagination.page,
        per_page: pagination.per_page,
        username: filters.username || undefined,
        email: filters.email || undefined,
        status: filters.status,
        role_id: filters.role_id,
      })
      users.value = data.items
      pagination.total = data.total
      pagination.page = data.page
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : '获取用户列表失败'
      message.error(msg)
    } finally {
      loading.value = false
    }
  }

  function resetFilters() {
    filters.username = ''
    filters.email = ''
    filters.status = undefined
    filters.role_id = undefined
    pagination.page = 1
  }

  async function fetchUserDataScope(userId: number): Promise<UserDataScope> {
    return api.get<UserDataScope>(`/api/v1/users/${userId}/data-scope`)
  }

  async function saveUserDataScope(userId: number, scopes: Omit<ScopeRecord, 'name'>[]) {
    await api.put(`/api/v1/users/${userId}/data-scope`, { scopes })
  }

  async function toggleApiKeyEnabled(userId: number, enabled: boolean) {
    await api.patch(`/api/v1/users/${userId}/api-key-enabled`, { api_key_enabled: enabled })
  }

  return {
    users,
    loading,
    pagination,
    filters,
    fetchUsers,
    resetFilters,
    fetchUserDataScope,
    saveUserDataScope,
    toggleApiKeyEnabled,
  }
})
