'use strict';

const bcrypt = require('bcryptjs');

/** @type {import('sequelize-cli').Migration} */
module.exports = {
  async up(queryInterface, Sequelize) {
    const users = [
      {
        name: 'Admin',
        username: 'admin',
        rawPassword: 'admin',
        role_id: 1,
      },
      {
        name: 'Support Internal',
        username: 'support_internal',
        rawPassword: 'support',
        role_id: 2,
      },
      {
        name: 'Support Client',
        username: 'support_client',
        rawPassword: 'support',
        role_id: 3,
      },
    ];

    for (const user of users) {
      const [existing] = await queryInterface.sequelize.query(
        `SELECT 1 FROM "pik_master"."user_panel" WHERE username = :username LIMIT 1`,
        {
          replacements: { username: user.username },
          type: Sequelize.QueryTypes.SELECT,
        }
      );

      if (!existing) {
        const hashedPassword = await bcrypt.hash(user.rawPassword, 10);

        await queryInterface.bulkInsert(
          { tableName: 'user_panel', schema: 'pik_master' },
          [
            {
              name: user.name,
              username: user.username,
              password: hashedPassword,
              role_id: user.role_id,
              created_at: new Date(),
              updated_at: new Date(),
            },
          ]
        );
      }
    }
  },

  async down(queryInterface, Sequelize) {
    await queryInterface.bulkDelete(
      { tableName: 'user_panel', schema: 'pik_master' },
      {
        username: ['admin', 'support_internal', 'support_client'],
      }
    );
  },
};
