import { makeRequest } from "@frontend/kitui"

import { jsonToFormdata } from "@root/utils/jsonToFormdata"
import { parseAxiosError } from "@root/utils/parse-error"

import type {
	Verification,
	SendDocumentsArgs,
	UpdateDocumentsArgs,
} from "@root/model/auth"
import { AxiosError } from "axios"

const apiUrl = process.env.REACT_APP_DOMAIN + "/verification"

export async function verification(
	userId: string
): Promise<[Verification | null, string?]> {
	try {
		const verificationResponse = await makeRequest<never, Verification>({
			url: apiUrl + "/verification/" + userId,
			method: "GET",
			useToken: true,
			withCredentials: true,
		})

		verificationResponse.files = verificationResponse.files.map((obj) => {
			obj.url = obj.url.replace("https://hub.pena.digital", process.env.REACT_APP_DOMAIN?.toString() || "").replace("https://shub.pena.digital", process.env.REACT_APP_DOMAIN?.toString() || "")
			return obj
		})
		console.log(verificationResponse)

		return [verificationResponse]
	} catch (nativeError) {
		const err = nativeError as AxiosError
		if (err.response?.status === 404) {
			return [null, `нет данных`]
		}
		console.log(nativeError)
		const [error] = parseAxiosError(nativeError)

		return [null, `Ошибка запроса верификации. ${error}`]
	}
}

export async function sendDocuments(
	documents: SendDocumentsArgs
): Promise<[Verification | "OK" | null, string?]> {
	try {
		const sendDocumentsResponse = await makeRequest<FormData, Verification>({
			url: apiUrl + "/verification",
			method: "POST",
			useToken: true,
			withCredentials: true,
			body: jsonToFormdata({ ...documents, egrule: documents.inn }),
		})

		return [sendDocumentsResponse]
	} catch (nativeError) {
		const [error] = parseAxiosError(nativeError)

		return [null, `Ошибка отправки документов. ${error}`]
	}
}

export async function updateDocuments(
	documents: UpdateDocumentsArgs
): Promise<[Verification | "OK" | null, string? ]> {
	try {
		const updateDocumentsResponse = await makeRequest<FormData, Verification>({
			url: apiUrl + "/verification/file",
			method: "PATCH",
			useToken: true,
			withCredentials: true,
			body: jsonToFormdata(
				documents.inn ? { ...documents, egrule: documents.inn } : documents
			),
		})

		return [updateDocumentsResponse]
	} catch (nativeError) {
		const [error] = parseAxiosError(nativeError)

		return [null, `Ошибка обновления документов. ${error}`]
	}
}
