'use strict';

const { sql } = require('../../db');
const { qname, inspectTables, requireColumns } = require('../softrestaurantIntrospection');

async function extract(pool, watermark, limit) {
  const metadata = await inspectTables(pool, { almacen: ['idalmacen', 'nombre', 'idempresa', 'tipo'] });
  const errors = requireColumns(metadata, 'almacen', ['idalmacen']);
  if (errors.length) return [];
  const hasIdEmpresa = metadata.tables.almacen.columns.idempresa;
  const hasTipo = metadata.tables.almacen.columns.tipo;
  const result = await pool.request()
    .input('limit', sql.Int, limit)
    .query(`
      SELECT TOP (@limit)
        CAST(a.idalmacen AS varchar(80)) AS external_id,
        NULL AS source_created_at,
        CAST('2000-01-01' AS datetime) AS source_updated_at,
        NULL AS business_date,
        a.idalmacen,
        ${metadata.tables.almacen.columns.nombre ? 'a.nombre' : 'CAST(a.idalmacen AS varchar(30))'} AS nombre,
        ${hasIdEmpresa ? 'a.idempresa' : 'NULL'} AS idempresa,
        ${hasTipo ? 'a.tipo' : 'NULL'} AS tipo
      FROM ${qname('almacen')} a
      ORDER BY a.idalmacen
    `);
  return result.recordset.map((row) => ({ ...row, payload: row }));
}

module.exports = { entityType: 'warehouses', extract };
