const express = require("express");
const Database = require("better-sqlite3");
const path = require("path");

const router = express.Router();

const mbtilesPath = path.join(__dirname, "..", "data", "raster.mbtiles");
const tileDb = new Database(mbtilesPath, { readonly: true });

const metadataRows = tileDb.prepare("SELECT name, value FROM metadata").all();
const metadata = {};

for (const row of metadataRows) {
    metadata[row.name] = row.value;
}

let contentType = "application/octet-stream";
if (metadata.format === "png") {
    contentType = "image/png";
} else if (metadata.format === "jpg" || metadata.format === "jpeg") {
    contentType = "image/jpeg";
} else if (metadata.format === "webp") {
    contentType = "image/webp";
}

router.get("/metadata/info", (req, res) => {
    res.json(metadata);
});

router.get("/:z/:x/:y", (req, res) => {
    const z = Number(req.params.z);
    const x = Number(req.params.x);
    const y = Number(req.params.y);

    if (!Number.isInteger(z) || !Number.isInteger(x) || !Number.isInteger(y)) {
        return res.status(400).json({ error: "Invalid tile coordinates" });
    }

    const tmsY = (1 << z) - 1 - y;

    const tile = tileDb.prepare(`
        SELECT tile_data
        FROM tiles
        WHERE zoom_level = ?
          AND tile_column = ?
          AND tile_row = ?
    `).get(z, x, tmsY);

    if (!tile) {
        return res.status(404).json({ error: "Tile not found" });
    }

    res.setHeader("Content-Type", contentType);
    res.send(tile.tile_data);
});

module.exports = router;
