import { pgClients, getTemplatePath, getTemplate } from "@opengis/fastify-table/utils.js";
const pg = pgClients.client;

export default async function gisRegistryList(req = {}) {
    const { query = {} } = req;
    const { page = 1, limit = 9, search = '' } = query;
    const offset = limit * (page - 1);

    const dbResult = await pg.query(
        `SELECT register_key, name, description, keywords
        FROM gis.registers
        WHERE is_public = true AND is_active = true`
    );

    let templates = dbResult?.rows;
    let fromDatabase = true;
    
    if (!templates?.length) {
        fromDatabase = false;

        const registryListTemplate = await getTemplatePath('registry');
        if (!registryListTemplate?.length) throw new Error('Templates not found');

        templates = ( await Promise.all(
            registryListTemplate.map(async ([slug]) => {
                try {
                    const tpl = await getTemplate('registry', slug);
                    if (tpl?.visible === false) return null;

                    const { register_key, name, description, keywords } = tpl;
                    return { register_key, name, description, keywords };
                } catch {
                    return null;
                }
            })
        ));
    }

    const filteredBySearch = search
        ? templates.filter(tpl => {
            const q = search.toLowerCase();
            return (
                tpl.name?.toLowerCase().includes(q) ||
                tpl.description?.toLowerCase().includes(q) ||
                tpl.keywords?.join(' ').toLowerCase().includes(q)
            );
        })
        : templates;

    const paged = filteredBySearch.slice(offset, offset + limit);

    return {
        rows: paged,
        total: filteredBySearch.length,
        page: parseInt(page, 10),
        limit: parseInt(limit, 10),
        offset
    };
}
