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

import { handleRegistryRequest } from './funcs/handleRegistryRequest.js';

const maxLimit = 100;
const defaultLimit = 9;

export default async function gisRegistry({
  pg = pgClients.client, params = {}, query = {},
}) {
  const { slug, objectId } = params;
  const { sql } = query;

  const limit = Math.min(query.limit || defaultLimit, maxLimit);
  const offset = query.page && query.page > 0 && !objectId ? (query.page - 1) * limit : 0;

  // if (!slug) return reply.code(404).send({ message: 'Params slug is required', status: 404 });
  if (!slug) throw new Error('Params slug is required');

  const {
    rows: [registry],
  } = await pg.query(
    `SELECT register_id, name, description, card, table_name,
            columns, filters, query, "order", pk, register_key, 
            is_files, view, is_downloadable, is_map, is_register, service_id
        FROM gis.registers
        WHERE  $1 in (register_key,register_id)`,
    [slug],
  );

  if (registry) {
    return handleRegistryRequest({
      settings: registry,
      query,
      object_id: objectId,
      offset,
      limit,
      page: query.page,
      pg,
      sql,
    });
  }

  const registryTemplate = await getTemplate('registry', slug);
  // if (!registryTemplate) return reply.code(404).send({ message: 'Template not found', status: 404 });
  if (!registryTemplate) throw new Error('Template not found');

  return handleRegistryRequest({
    settings: registryTemplate,
    query,
    object_id: objectId,
    register_key: registry.register_key,
    is_downloadable: registry?.is_downloadable || registryTemplate?.is_downloadable,
    is_map: registryTemplate.is_map,
    is_register: registryTemplate.is_register,
    is_files: registryTemplate.is_files,
    service_id: registryTemplate.service_id,
    offset,
    limit,
    page: query.page,
    pg,
    sql,
  });
}
