const mysql = require('mysql2');
const { queryDb } = require("../helpers/db");


const locationHandler = async (req, res) => {
    const slug = mysql.escape(req.params?.slug);
    const query = `SELECT * FROM Locations WHERE slug = ${slug}`
    const location = await queryDb(query)
    if (!location?.[0]?.id) {
        res.status(404).render("pages/404View")
        return
    }
    res.locals.location = location

    res.render('location/locationDetailsView');
}

const locationHandlerPostalCode = async (req, res) => {
    const postalDistrict = req.params?.postal_district;
    console.log(`Postal District: ${postalDistrict}`);
    // Ensure postalDistrict is safe to use in a query
    if (!postalDistrict || typeof postalDistrict !== 'string' || !/^[a-zA-Z0-9-]+$/.test(postalDistrict)) {
        res.status(400).send('Invalid postal district');
        return;
    }

    // Construct the query safely
    const query = `SELECT * FROM locations WHERE postal_code LIKE '${postalDistrict}'`;
    const locations = await queryDb(query);

    // Handle no results
    if (!locations.length) {
        res.status(404).render("pages/404View");
        return;
    }

    // Pass locations to the view
    res.locals.locations = locations;
    console.log(`Query: ${query}`);
    console.log(`Locations:`, locations);

    // Render the view
    res.render('location/areaDistrictView');
}



module.exports = {
    locationHandler,
    locationHandlerPostalCode
}