const {request} = require("../utils/request")
const {render, instance} = require("pinski/plugins")
const {getUser} = require("../utils/getuser")
const fetch = require("node-fetch")
const converters = require("../utils/converters")
const dearrow = require("../eirtubeMods/sb")

module.exports = [
	{
		route: "/(?:search|results)", methods: ["GET"], code: async ({req, url}) => {
			const query = url.searchParams.get("q") || url.searchParams.get("search_query")
			const user = getUser(req)
			const settings = user.getSettingsOrDefaults()
			const instanceOrigin = settings.instance

			const fetchURL = new URL(`${instanceOrigin}/api/v1/search`)
			fetchURL.searchParams.set("q", query)

			// Fetch search results
			let q = await request(fetchURL.toString())
			if (!q.ok) {
				// Has error
				if (q.result.message) {
					if (q.result instanceof fetch.FetchError)
						return render(500, "pug/errors/fetch-error.pug", { instanceOrigin, error: q.result })
					else
						return render(500, "pug/errors/message-error.pug", { instanceOrigin, error: q.result })
				// Just didn't return json
				} else {
					const out = await q.result.text()
					// html
					if (out.indexOf("<head>") != -1)
						return render(q.result.status, `pug/errors/substitute-html-error.pug`, { content: out })
					// just text
					else
						return render(q.result.status, "pugs/errors/message-error.pug", { instanceOrigin, error: new Error(out) })
				}
			}

			let results = q.result
			const error = results.error || results.message || results.code

			if (error) throw new Error(`Instance said: ${error}`)

			for (const video of results) {
				converters.normaliseVideoInfo(video)
			}

			let toasts = []
			// Apply DeArrow data
			if (settings.dearrow > 0) {
				if (settings.dearrow_preload == 1) {
					const dearrowOut = await dearrow.applyToAllDeArrow(results)
					if (Object.keys(dearrowOut.errors).length > 0)
						for (const deE of Object.keys(dearrowOut.errors))
							toasts.push({ color: "red", icon: "x", text: dearrowOut.errors[deE] })
				} else
					dearrow.getAllDeArrowNoBlock(results)
			}

			const filters = user.getFilters()
			results = converters.applyVideoFilters(results, filters).videos

			return render(200, "pug/search.pug", {req, settings, url, query, results, instanceOrigin, toasts})
		}
	}
]
