import { get, post } from '@/core/http/http-client'
import { fetchUploadConfig, uploadImageFile } from '@/features/dynamics/publish-gateway'

const ROUTE_REASONS = '/wanlshop/complaint/reasonlist'
const ROUTE_ADD = '/wanlshop/complaint/add'
const ROUTE_LISTS = '/wanlshop/complaint/lists'

function unwrapListPageBody(data, raw) {
	const candidates = [data, raw?.data, raw?.res?.data]
	for (const c of candidates) {
		if (!c || typeof c !== 'object' || Array.isArray(c)) continue
		if (Array.isArray(c.data) || c.current_page != null || c.last_page != null) {
			return c
		}
		if (c.data && typeof c.data === 'object' && !Array.isArray(c.data)) {
			const inner = c.data
			if (Array.isArray(inner.data) || inner.current_page != null) return inner
		}
	}
	return { data: [], current_page: 1, last_page: 1, total: 0 }
}

function normalizeReasonRow(item) {
	if (!item || item.title == null) return null
	const code = Number(item.code_num)
	if (Number.isNaN(code)) return null
	return { code_num: code, title: String(item.title) }
}

/**
 * @param {Record<string, string>} option 路由 query
 * @param {(key: string) => string} t
 */
export function buildComplaintDraft(option = {}, t) {
	const type = option.type != null && option.type !== '' ? Number(option.type) : 0
	const id = option.id != null && option.id !== '' ? Number(option.id) : 0
	const draft = {
		type: Number.isNaN(type) ? 0 : type,
		complaint_user_id: 0,
		complaint_shop_id: 0,
		complaint_goods_id: 0,
		images: [],
		content: '',
		reason: -1
	}
	let typeName = t('complaint.typeGeneral')

	if (draft.type === 0) {
		typeName = t('complaint.types.user')
		draft.complaint_user_id = id
	} else if (draft.type === 1) {
		typeName = t('complaint.types.product')
		draft.complaint_goods_id = id
	} else if (draft.type === 2) {
		typeName = t('complaint.types.shop')
		draft.complaint_shop_id = id
	} else if (draft.type === 3) {
		typeName = t('complaint.types.group')
		draft.complaint_goods_id = id
	}

	let content = ''
	if (option.content != null && String(option.content).trim() !== '') {
		content = String(option.content)
		try {
			content = decodeURIComponent(content)
		} catch (_) {}
		draft.content = content.trim()
	}

	return {
		draft,
		typeName,
		targetId: id
	}
}

export async function fetchComplaintReasons() {
	const { data, raw } = await get(ROUTE_REASONS)
	const list = Array.isArray(data) ? data : Array.isArray(raw?.data) ? raw.data : []
	return list.map(normalizeReasonRow).filter(Boolean)
}

export async function submitComplaint(payload) {
	const { data, msg } = await post(ROUTE_ADD, payload)
	return { data, msg }
}

export async function fetchComplaintListPage(page = 1) {
	const { data, raw } = await get(ROUTE_LISTS, { page })
	const body = unwrapListPageBody(data, raw)
	const rows = Array.isArray(body.data) ? body.data : []
	return {
		rows,
		total: Number(body.total || rows.length),
		currentPage: Number(body.current_page || page || 1),
		lastPage: Number(body.last_page || body.current_page || 1)
	}
}

export async function uploadComplaintImage(filePath) {
	const config = await fetchUploadConfig()
	return uploadImageFile(filePath, config)
}
