import { getMeta, pgClients } from "@opengis/fastify-table/utils.js";

const table = 'gis.widgets';

const columnType = {
    text: 'text',
    date: 'date',
    bool: 'yes/no',
    numeric: 'number',
    integer: 'number',
    'timestamp without time zone': 'date',
    'timestamp with time zone': 'date',
};

export default async function getWidget({ params = {}, pg = pgClients.client }, reply) {
    if (!params.map) {
        return reply.status(400).send('not enough params: map id');
    }

    const { columns = [] } = await getMeta({ pg, table }) || {};

    const fields = columns.map(({ name, dataTypeID, title }) => ({ name, type: columnType[pg.pgType?.[dataTypeID] || 'text'], label: title || name }));

    const rows = pg.pk?.['gis.maps'] && pg.pk?.['gis.widgets'] ? await pg.query(
        `SELECT widget_id as id, * FROM gis.widgets where map_id=$1 and ${params.id ? 'widget_id=$2' : '1=1'}`,
        [params.map, params.id].filter(Boolean),
    ).then(el => el.rows || []) : [];

    if (params.id && !rows.length) {
        return reply.status(404).send('widget not found');
    }

    if (params.id) {
        return reply.status(200).send({ ...rows[0], fields });
    }

    return reply.status(200).send({
        rows,
        fields,
    });
}