import { Tariff, makeRequest } from "@frontend/kitui"
import { parseAxiosError } from "@root/utils/parse-error"

export interface GetHistoryResponse {
	totalPages: number;
	records: HistoryRecord[];
}

export type HistoryRecord = {
	comment: string;
	createdAt: string;
	id: string;
	isDeleted: boolean;
	key: string;
	rawDetails: [RawDetails, KeyValue];
	updatedAt: string;
	userId: string;
};

export interface GetHistoryResponse2 {
	totalPages: number;
	records: HistoryRecord[];
}

export type HistoryRecord2 = {
	comment: string;
	createdAt: string;
	id: string;
	isDeleted: boolean;
	key: string;
	rawDetails: {
        price: number;
        tariffs: Tariff[];
    };
	updatedAt: string;
	userId: string;
};

type RawDetails = { Key: string; Value: KeyValue[][] }
type KeyValue = { Key: string; Value: string | number };

const regList:Record<string, number> = {
	"tariffs": 0,
	"price": 1
}

export async function getHistory(): Promise<[GetHistoryResponse | GetHistoryResponse2 | null, string?]> {
	try {
		const historyResponse = await makeRequest<never, GetHistoryResponse>({
			url: process.env.REACT_APP_DOMAIN + "/customer/history?page=1&limit=100&type=payCart",
			method: "get",
			useToken: true,
		})

        if (!Array.isArray(historyResponse.records[0]?.rawDetails)) {
            return [historyResponse] as [GetHistoryResponse2]
        }

		const checked = historyResponse.records.map((data) => {
			console.log(data.rawDetails)
			const buffer:KeyValue[] = []
			data.rawDetails.forEach((slot) => {
				let index = regList[slot.Key as string]
				//@ts-ignore
				buffer[index] = { Key: slot.Key, Value: slot.Value }
			})
			//Чистим дыры с помощью .filter(() => true) но нужно ли это
				console.log("Я собираюсь вкладывать такой буфер равдетайлс", buffer)
				//@ts-ignore
			data.rawDetails = buffer
			return data
		})


		historyResponse.records = checked || []
		return [historyResponse]
	} catch (nativeError) {
		const [error] = parseAxiosError(nativeError)

		return [null, `Не удалось получить историю. ${error}`]
	}
}
