import { Router } from "express";
import * as XLSX from "xlsx";
import { apiReturn } from "../utils/returnHelper.utils.js";
import { runDatamartQuery } from "./datamart.controller.js";

const r = Router();

type Options = {
	name: string;
	value: string;
	format: string;
};

r.get("/:name", async (req, res) => {
	const { name } = req.params;
	const options = { ...req.query } as Options;
	const dataRan = await runDatamartQuery({ name, options });

	if (!dataRan.success) {
		return apiReturn(res, {
			success: false,
			level: "error",
			module: "datamart",
			subModule: "query",
			message: dataRan.message,
			status: 500,
		});
	}

	// XLSX Export
	if (options.format?.toLowerCase() === "xlsx") {
		const wb = XLSX.utils.book_new();

		const ws = XLSX.utils.json_to_sheet(dataRan.data);

		XLSX.utils.book_append_sheet(wb, ws, name);

		const buffer = XLSX.write(wb, {
			type: "buffer",
			bookType: "xlsx",
		});

		res.setHeader(
			"Content-Type",
			"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
		);

		res.setHeader("Content-Disposition", `attachment; filename="${name}.xlsx"`);

		return res.send(buffer);
	}

	// CSV Export
	if (options.format?.toLowerCase() === "csv") {
		const rows = dataRan.data as any;

		if (!rows.length) {
			return res.status(200).send("");
		}

		const headers = Object.keys(rows[0]);

		const csv = [
			headers.join(","),
			...rows.map((row: any) =>
				headers
					.map((h) => `"${String(row[h] ?? "").replace(/"/g, '""')}"`)
					.join(","),
			),
		].join("\r\n");

		res.setHeader("Content-Type", "text/csv");
		res.setHeader("Content-Disposition", `attachment; filename="${name}.csv"`);

		return res.send(csv);
	}

	return apiReturn(res, {
		success: dataRan.success,
		level: "info",
		module: "datamart",
		subModule: "query",
		message: dataRan.message,
		data: dataRan.data,
		status: 200,
	});
});

export default r;
