import {parseProductDetail} from "../lib/parseProductDetail";
import {parseProductDetailError} from "../lib/parseProductDetailError";
import {cacheFetch} from "../lib/cacheFetch";
import {ApiUrlBase, InvalidIdError} from "/src-com";
import {isProductId} from "../lib/isProductId";

export async function executeDetail(id: string | number): Promise<any> {
	if (!isProductId(id)) {
		throw new InvalidIdError(id);
	}
	const resp = await cacheFetch(`https://auctions.yahoo.co.jp/jp/auction/${id}`);
	const text = await resp.text();
	if (resp.ok) {
		return parseProductDetail(text);
	}
	let data: any = {};
	if (resp.status === 404) {
		data = parseProductDetail(text)
	}
	if (/html/.test(resp.headers.get('content-type'))) {
		data.error = parseProductDetailError(text)
	} else {
		data.error = resp.statusText || text
	}
	return data;
}

export async function commitDetailTask(rwid: number | string, dataList: any[]): Promise<any> {
	const url = `${ApiUrlBase}/searchGoods/callbackTaskDetail`;
	return await fetch(url, {
		method: 'POST',
		headers: {
			'Content-Type': 'application/json'
		},
		body: JSON.stringify({rwid, dataList})
	}).then(r => r.json());
}
