'use strict';

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

async function extract(pool, watermark, limit) {
  const metadata = await inspectTables(pool, {
    movtosalmacen: ['fecha', 'movto', 'idcompra', 'traspaso', 'invfisico', 'idconcepto', 'idinsumospresentaciones', 'costo', 'cantidad', 'idalmacen'],
    movsinv: ['fecha', 'movto', 'foliocheque', 'idcompra', 'traspaso', 'invfisico', 'idconcepto', 'idinsumo', 'costo', 'cantidad', 'idalmacen'],
  });
  const queries = [];
  if (!requireColumns(metadata, 'movtosalmacen', ['fecha', 'idinsumospresentaciones', 'cantidad', 'idalmacen']).length) {
    queries.push(`
      SELECT TOP (@limit)
        CAST(CONCAT('movtosalmacen-', CONVERT(varchar(23), fecha, 126), '-', ISNULL(CAST(movto AS varchar(30)), '0'), '-', ISNULL(idalmacen, ''), '-', ISNULL(idinsumospresentaciones, '')) AS varchar(220)) AS external_id,
        fecha AS source_created_at,
        fecha AS source_updated_at,
        CAST(fecha AS date) AS business_date,
        'movtosalmacen' AS source_table,
        idalmacen,
        idinsumospresentaciones,
        CAST(NULL AS varchar(15)) AS idinsumo,
        cantidad,
        costo,
        idconcepto,
        movto,
        idcompra,
        traspaso,
        invfisico
      FROM ${qname('movtosalmacen')}
      WHERE fecha > @last
    `);
  }
  if (!requireColumns(metadata, 'movsinv', ['fecha', 'idinsumo', 'cantidad', 'idalmacen']).length) {
    queries.push(`
      SELECT TOP (@limit)
        CAST(CONCAT('movsinv-', CONVERT(varchar(23), fecha, 126), '-', ISNULL(CAST(movto AS varchar(30)), '0'), '-', ISNULL(idalmacen, ''), '-', ISNULL(idinsumo, '')) AS varchar(220)) AS external_id,
        fecha AS source_created_at,
        fecha AS source_updated_at,
        CAST(fecha AS date) AS business_date,
        'movsinv' AS source_table,
        idalmacen,
        CAST(NULL AS varchar(15)) AS idinsumospresentaciones,
        idinsumo,
        cantidad,
        costo,
        idconcepto,
        movto,
        idcompra,
        traspaso,
        invfisico
      FROM ${qname('movsinv')}
      WHERE fecha > @last
    `);
  }
  if (!queries.length) return [];
  const result = await pool.request()
    .input('last', sql.DateTime, watermark ? new Date(watermark) : new Date('2000-01-01T00:00:00'))
    .input('limit', sql.Int, Math.max(1, Math.floor((limit || 100) / queries.length)))
    .query(`${queries.join('\nUNION ALL\n')}\nORDER BY source_updated_at`);
  return result.recordset.map((row) => ({ ...row, payload: row }));
}

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