import { get, post } from '@/core/http/http-client'

const ROUTE_LIST = '/wanlshop/user/blockedList'
const ROUTE_TOGGLE = '/wanlshop/user/blockedUser'
const ROUTE_IS_BLOCKED = '/wanlshop/user/isblocked'

function parseIsBlocked(payload) {
	if (!payload || typeof payload !== 'object') return false
	if (payload.is_blocked !== undefined) return Number(payload.is_blocked) === 1
	if (payload.data && payload.data.is_blocked !== undefined) {
		return Number(payload.data.is_blocked) === 1
	}
	return false
}

function normalizeBlockedList(payload) {
	if (Array.isArray(payload)) return payload
	if (!payload || typeof payload !== 'object') return []
	if (Array.isArray(payload.data)) return payload.data
	if (Array.isArray(payload.list)) return payload.list
	return []
}

export function blockedUserAvatar(item) {
	return (
		(item && item.blocked_user && item.blocked_user.avatar) ||
		(item && item.user && item.user.avatar) ||
		''
	)
}

export function blockedUserId(item) {
	const id =
		(item && item.blocked_id) ||
		(item && item.blocked_user && item.blocked_user.id) ||
		(item && item.user && item.user.id)
	if (id == null || id === '') return ''
	return id
}

export function blockedUserNickname(item, fallback = '') {
	return (
		(item && item.blocked_user && item.blocked_user.nickname) ||
		(item && item.user && item.user.nickname) ||
		fallback
	)
}

export async function fetchBlockedList() {
	const { data, raw } = await get(ROUTE_LIST)
	if (Array.isArray(data)) return data
	const payload = data != null ? data : raw?.data
	if (Array.isArray(payload)) return payload
	if (payload && Array.isArray(payload.list)) return payload.list
	return normalizeBlockedList(payload)
}

/**
 * 查询当前登录用户是否已拉黑目标用户。
 * @param {string|number} userNo 目标 user_no
 * @param {string|number} blockedUserId 目标用户数据库 id
 */
export async function fetchIsBlocked(userNo, blockedUserId) {
	if (!userNo || blockedUserId == null || blockedUserId === '') return false
	const { data, raw } = await post(ROUTE_IS_BLOCKED, {
		user_no: userNo,
		blocked_id: blockedUserId
	})
	const payload = data != null ? data : raw?.data
	return parseIsBlocked(payload)
}

/** @param {string|number} blockedId @param {0|1} handType 0 取消拉黑 1 拉黑 */
export async function toggleBlockedUser(blockedId, handType) {
	const { data, msg } = await post(ROUTE_TOGGLE, {
		blocked_id: blockedId,
		hand_type: handType
	})
	return { data, msg }
}

/** @param {string|number} blockedId */
export async function blockUser(blockedId) {
	return toggleBlockedUser(blockedId, 1)
}

/** @param {string|number} blockedId */
export async function unblockUser(blockedId) {
	return toggleBlockedUser(blockedId, 0)
}
