import { pgClients, getFilterSQL, getTemplate } from "@opengis/fastify-table/utils.js";
import { attachClassifiers } from './funcs/classifiers.js';
const pg = pgClients.client;

export default async function mapRegistry(req,reply) {
const { params = {}, query = {} } = req;
    const { slug, id } = params;
    const { filter, page = 1 } = query;

    if (!slug || !id) return reply.code(404).send({ message: 'Params slug and id is required', status: 404 });

    const mapTemplate = await getTemplate('map', slug);
    if (!mapTemplate) return reply.code(404).send({ message: 'Template not found', status: 404 });

    const listWidget = mapTemplate.widgets?.find(w => w.type === 'list' && w.visible !== false && w.id === id);
    if (!listWidget) return reply.code(404).send({ message: 'List widget not found', status: 404 });

    const {
        table,
        pk,
        query: baseQuery = '1=1',
        order,
        config = {},
        name = '',
    } = listWidget;

    const { columns = [], filters = [], limit: configLimit = 20 } = config;
    const limit = query.limit || configLimit;
    const offset = limit * (page - 1);
    const selectColumns = columns.map(col => col.name);

    const classifiers = columns
        .filter(col => col.data && ["select", "badge", "tags"].includes(col.format))
        .map(col => ({ name: col.name, classifier: col.data }));


    const { q: sqlFilter } = filter
        ? await getFilterSQL({ table, filter, json: 1 })
        : { q: '1=1' };

    const whereConditions = [baseQuery, sqlFilter].filter(Boolean).join(" AND ");
    const whereClause = whereConditions ? `WHERE ${whereConditions}` : "";

    const sqlBase = `FROM ${table} ${whereClause}`;
    const sqlOrder = order ? `ORDER BY ${order}` : "";
    const sqlLimit = `LIMIT $1 OFFSET $2`;
    const sqlSelect = `SELECT ${pk} as id, ${selectColumns.join(", ")} 
    ${sqlBase}`;
    const dataQuery = `${sqlSelect} ${sqlOrder} ${sqlLimit}`;
    const totalQuery = `SELECT COUNT(*) ${sqlBase}`;

    const [dataRes, countRes] = await Promise.all([
        pg.query(dataQuery, [limit, offset]),
        pg.query(totalQuery)
    ]);

    const rows = await attachClassifiers(dataRes?.rows, classifiers);
    const total = parseInt(countRes?.rows[0]?.count || 0, 10);

    const listViewConfig = {};
    columns.forEach(col => {
        if (col.view_type === 'title') listViewConfig.title = col?.name;
        if (col.view_type === 'subtitle') listViewConfig.subtitle = col?.name;
    });

    return {
        name,
        rows,
        total,
        columns,
        filters,
        config: {
            ...listWidget,
            list: {
                ...listViewConfig
            }
        }
    };
}
