import { LOG } from "@logger";
import base64 from "react-native-base64";
import axiosRequest from "../axiosRequest";
import type { PaymentCode } from "./types";

const log = LOG.extend("transactions");

export interface Transaction {
	// biome-ignore lint/style/useNamingConvention: <api response>
	type_paiement: number;
	// biome-ignore lint/style/useNamingConvention: <api response>
	type_paiement_label: PaymentCode;
	marchand: string;
	// biome-ignore lint/style/useNamingConvention: <api response>
	marchand_name: string;
	service: string;
	montant: number;
	date: string;
	commentaire: string;
	etat: boolean;
	status: "SUCCESS" | "INITIATED" | "FAILED";
	reference: string;
	// biome-ignore lint/style/useNamingConvention: <api response>
	transaction_id: number;
	// biome-ignore lint/style/useNamingConvention: <api response>
	marchand_code: string;
}

export interface TransactionHistoryResponse {
	count: number;
	next: string | null;
	previous: string | null;
	results: Transaction[];
}

export const getTransactionsHistory = async (): Promise<Transaction[]> => {
	const basictoken = base64.encode("admin:admin");

	log.http("getTransactionsHistory");
	try {
		const response = await axiosRequest<TransactionHistoryResponse>({
			url: "/transactions/",
			headers: {
				// biome-ignore lint/style/useNamingConvention: <explanation>
				Authorization: `Basic ${basictoken}`,
			},
		});

		log.http("getTransactionsHistory |", JSON.stringify(response, null, 2));

		// TODO: Update this when the api is fixed, response  should not be reversed
		return response.results.reverse();
	} catch (error) {
		log.error("getTransactionsHistory |", error);
		throw error;
	}
};
