import express, { Request, Response } from 'express';
import { tediousQuery } from '../../utils/tedious';
import { GeneralDB, GisDB } from '../../constants/db';
const router = express.Router()

router.get('/images/all', async (req: Request, res: Response) => {
    try {
        const { offset, limit, city_id } = req.query

        const result = await tediousQuery(
            `
            SELECT * FROM ${GisDB}..images
            ${city_id ? `WHERE city_id = ${city_id}` : ''}
            ORDER BY city_id 
            OFFSET ${Number(offset) || 0} ROWS
            FETCH NEXT ${Number(limit) || 10} ROWS ONLY;
            `
        )
        res.status(200).json(result)
    } catch (err) {
        res.status(500)
    }
})


// Get figures by year and city id
router.get('/figures/all', async (req: Request, res: Response) => {
    try {
        const { offset, limit, object_id, year, city_id } = req.query

        const result = await tediousQuery(
            `
            SELECT * FROM ${GisDB}..figures f
            JOIN ${GeneralDB}..vObjects o ON f.object_id = o.object_id WHERE o.id_city = ${city_id} AND f.year = ${year}
            ORDER BY f.year
            OFFSET ${Number(offset) || 0} ROWS
            FETCH NEXT ${Number(limit) || 10} ROWS ONLY;
            `
        )
        res.status(200).json(result)
    } catch (err) {
        res.status(500)
    }
})

// Get lines by year and city id
router.get('/lines/all', async (req: Request, res: Response) => {
    try {
        const { offset, limit, object_id, year, city_id } = req.query

        const result = await tediousQuery(
            `
            SELECT * FROM ${GisDB}..lines l
            JOIN ${GeneralDB}..vObjects o ON l.object_id = o.object_id WHERE o.id_city = ${city_id} AND l.year = ${year};
            `
        )
        res.status(200).json(result)
    } catch (err) {
        res.status(500)
    }
})

router.get('/regions/borders', async (req: Request, res: Response) => {
    try {
        const result = await tediousQuery(
            `
            SELECT * FROM ${GisDB}..visual_regions`
        )
        res.status(200).json(result)
    } catch (err) {
        res.status(500)
    }
})

export default router