'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    const numeros = ['12345', '67890', '11223', '44556'];
    const [nfRows] = await queryInterface.sequelize.query(
      `SELECT id, numero_nf FROM notas_fiscais WHERE numero_nf IN (:nums)`,
      { replacements: { nums: numeros } }
    );
    const nfMap = new Map(nfRows.map(r => [r.numero_nf, r.id]));

    const entries = [
      // NF 12345
      { nf_num: '12345', status: 'Pendente', date: '2024-07-15T10:00:00Z', user: 'Diligenciador' },
      { nf_num: '12345', status: 'Recebido', date: '2024-07-18T14:30:00Z', user: 'Almoxarife' },
      { nf_num: '12345', status: 'Conferido', date: '2024-07-19T09:00:00Z', user: 'Conferente' },
      // NF 67890
      { nf_num: '67890', status: 'Pendente', date: '2024-07-16T11:00:00Z', user: 'Diligenciador' },
      { nf_num: '67890', status: 'Recebido', date: '2024-07-21T16:00:00Z', user: 'Almoxarife' },
      // NF 11223
      { nf_num: '11223', status: 'Pendente', date: '2024-07-20T08:30:00Z', user: 'Diligenciador' },
      // NF 44556
      { nf_num: '44556', status: 'Pendente', date: '2024-07-21T15:00:00Z', user: 'Diligenciador' },
    ];

    const allNfIds = Array.from(new Set(entries.map(e => nfMap.get(e.nf_num)).filter(Boolean)));
    let existingSet = new Set();
    if (allNfIds.length > 0) {
      const [histRows] = await queryInterface.sequelize.query(
        `SELECT nf_id, COUNT(*) AS cnt FROM nf_history WHERE nf_id IN (:ids) GROUP BY nf_id`,
        { replacements: { ids: allNfIds } }
      );
      existingSet = new Set(histRows.map(r => r.nf_id));
    }

    const records = entries
      .map(e => ({
        nf_id: nfMap.get(e.nf_num),
        status: e.status,
        date: new Date(e.date),
        user: e.user,
      }))
      .filter(r => r.nf_id && !existingSet.has(r.nf_id));

    if (records.length) {
      await queryInterface.bulkInsert('nf_history', records);
    }
  },

  async down(queryInterface, Sequelize) {
    await queryInterface.bulkDelete('nf_history', {
      status: { [Sequelize.Op.in]: ['Pendente', 'Recebido', 'Conferido'] },
    });
  },
};