import fs from "node:fs";
import { and, eq } from "drizzle-orm";
import { Router } from "express";
import path from "path";
import { db } from "../db/db.controller.js";
import { settings } from "../db/schema/settings.schema.js";

const router = Router();

const projectRoot = path.resolve("./lstMobile"); // adjust as needed
const appJsonPath = path.join(projectRoot, "app.json");

router.get("/", async (req, res) => {
	const baseUrl = `${req.protocol}://${req.get("host")}`;
	const mobileSettings = await db
		.select()
		.from(settings)
		.where(
			and(
				eq(settings.moduleName, "mobile"),
				eq(settings.settingType, "standard"),
			),
		);

	const raw = fs.readFileSync(appJsonPath, "utf-8");
	const config = JSON.parse(raw);

	const exp = config.expo;

	res.json({
		packageName: exp.android?.package,
		versionName: exp.version,
		versionCode: exp.android?.versionCode,
		minSupportedVersionCode: exp?.android?.minSupportedVersionCode ?? 0,
		downloadUrl: `${baseUrl}/lst/api/mobile/apk/latest`,
		settings: mobileSettings,
	});
});

export default router;
