import { apiClient } from '@/shared/api/client'

import type { ApiResponse, PaginatedResult } from '@/shared/types/types'

export interface AdminRole {
  id: number
  code: string
  name: string
  description: string
}

export interface AdminMgrUser {
  id: number
  username: string
  nickname: string
  status: string
  roles: AdminRole[]
  last_login_at?: string
  created_at: string
  updated_at: string
}

export interface CreateAdminRequest {
  username: string
  password: string
  nickname?: string
}

export interface UpdateAdminRequest {
  nickname?: string
  status?: string
}

export interface ChangePasswordRequest {
  old_password: string
  new_password: string
}

export async function fetchAdminMgrUsers(page = 1, pageSize = 20) {
  const { data } = await apiClient.get<ApiResponse<PaginatedResult<AdminMgrUser>>>('/admin/admin-users', {
    params: { page, page_size: pageSize },
  })
  return data.data
}

export async function fetchAdminMgrUser(id: number) {
  const { data } = await apiClient.get<ApiResponse<AdminMgrUser>>(`/admin/admin-users/${id}`)
  return data.data
}

export async function createAdminMgrUser(req: CreateAdminRequest) {
  const { data } = await apiClient.post<ApiResponse<AdminMgrUser>>('/admin/admin-users', req)
  return data.data
}

export async function updateAdminMgrUser(id: number, req: UpdateAdminRequest) {
  const { data } = await apiClient.put<ApiResponse<AdminMgrUser>>(`/admin/admin-users/${id}`, req)
  return data.data
}

export async function deleteAdminMgrUser(id: number) {
  const { data } = await apiClient.delete<ApiResponse<{ deleted: boolean }>>(`/admin/admin-users/${id}`)
  return data.data
}

export async function assignAdminRoles(id: number, roleIds: number[]) {
  const { data } = await apiClient.put<ApiResponse<{ updated: boolean }>>(`/admin/admin-users/${id}/roles`, {
    role_ids: roleIds,
  })
  return data.data
}

export async function changeAdminPassword(id: number, req: ChangePasswordRequest) {
  const { data } = await apiClient.put<ApiResponse<{ updated: boolean }>>(`/admin/admin-users/${id}/password`, req)
  return data.data
}
