import { api } from '@/core/services/api'
import type { PaginatedApiResponse } from '@/core/types/api'
import type {
  CreateUserPayload,
  ListDeletedUsersParams,
  ListUsersParams,
  UpdateUserPayload,
  UserDetail,
  UserListItem,
} from '../types/user.types'

type UserApiResponse = {
  success: boolean
  data: UserDetail
  message?: string
}

export async function listUsers(
  params: ListUsersParams,
): Promise<PaginatedApiResponse<UserListItem>> {
  const { data } = await api.get<PaginatedApiResponse<UserListItem>>('/v1/users', {
    params,
  })

  if (!data.success) {
    throw new Error(data.message ?? 'Failed to load users')
  }

  return data
}

export async function listDeletedUsers(
  params: ListDeletedUsersParams,
): Promise<PaginatedApiResponse<UserListItem>> {
  const { data } = await api.get<PaginatedApiResponse<UserListItem>>('/v1/users/deleted', {
    params,
  })

  if (!data.success) {
    throw new Error(data.message ?? 'Failed to load deleted users')
  }

  return data
}

export async function restoreUser(id: string): Promise<UserApiResponse> {
  const { data } = await api.post<UserApiResponse>(`/v1/users/${id}/restore`)

  if (!data.success) {
    throw new Error(data.message ?? 'Failed to restore user')
  }

  return data
}

export async function getUser(id: string): Promise<UserApiResponse> {
  const { data } = await api.get<UserApiResponse>(`/v1/users/${id}`)

  if (!data.success) {
    throw new Error(data.message ?? 'Failed to load user')
  }

  return data
}

export async function createUser(payload: CreateUserPayload): Promise<UserApiResponse> {
  const { data } = await api.post<UserApiResponse>('/v1/users', payload)

  if (!data.success) {
    throw new Error(data.message ?? 'Failed to create user')
  }

  return data
}

export async function updateUser(
  id: string,
  payload: UpdateUserPayload,
): Promise<UserApiResponse> {
  const { data } = await api.patch<UserApiResponse>(`/v1/users/${id}`, payload)

  if (!data.success) {
    throw new Error(data.message ?? 'Failed to update user')
  }

  return data
}

export async function deleteUser(id: string): Promise<UserApiResponse> {
  const { data } = await api.delete<UserApiResponse>(`/v1/users/${id}`)

  if (!data.success) {
    throw new Error(data.message ?? 'Failed to delete user')
  }

  return data
}

export async function assignUserRoles(
  id: string,
  roleIds: string[],
): Promise<UserApiResponse> {
  const { data } = await api.post<UserApiResponse>(`/v1/users/${id}/roles`, {
    roles: roleIds,
  })

  if (!data.success) {
    throw new Error(data.message ?? 'Failed to assign roles')
  }

  return data
}
