import fp from 'fastify-plugin';

import {
  config, addHook, getMeta, pgClients, execMigrations,
} from '@opengis/fastify-table/utils.js';

config.prefix = config.prefix || '/api';

import { join, dirname } from 'path';
import { fileURLToPath } from 'url';

const dir = dirname(fileURLToPath(import.meta.url));

execMigrations(join(dir, 'server/migrations'), pgClients.client).catch(err => console.error(err.toString()));

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

async function plugin(app, opts = config) {
  // API
  app.register(import('./server/routes/map/index.mjs'), opts);
  app.register(import('./server/plugins/crons.js'), opts);
  app.register(import('./server/routes/gis/index.mjs'), opts);
  app.register(import('./server/routes/mapnik/index.js'), opts);

  addHook('afterData', async ({
    pg = pgClients.client, payload, id, template,
  }) => {
    if (!template) return null;
    const table = { 'gis.services.table': payload?.rows?.[0]?.source_path, 'gis.registers.table': payload?.rows?.[0]?.table_name }[template];
    if (!table || !payload.columns?.length || !id || !pgClients?.client?.pk?.[table]) return null;

    const { columns = [] } = await getMeta({ table, pg });
    // payload.rows[0].token = payload.tokens?.edit; // token with ignore filtering of payload keys check
    Object.assign(payload, { fields: columns?.map?.(({ name, title, dataTypeID }) => ({ name, title: title || name, type: columnType[pg?.pgType?.[dataTypeID] || 'text'] })).filter(el => el.type) });
  });
}
export default fp(plugin);
