'use strict';

module.exports = {
  up: async (queryInterface, Sequelize) => {
    const createdAt = new Date();
    const updatedAt = new Date();

    const [publicRole] = await queryInterface.sequelize.query(
      "SELECT id FROM roles WHERE name = 'Public' LIMIT 1"
    );

    const [createLeadsPermission] = await queryInterface.sequelize.query(
      "SELECT id FROM permissions WHERE name = 'CREATE_LEADS' LIMIT 1"
    );

    if (publicRole.length && createLeadsPermission.length) {
        // Check if already exists
        const [existing] = await queryInterface.sequelize.query(
          `SELECT * FROM "rolesPermissionsPermissions" WHERE "roles_permissionsId" = '${publicRole[0].id}' AND "permissionId" = '${createLeadsPermission[0].id}'`
        );
        
        if (!existing.length) {
            await queryInterface.bulkInsert('rolesPermissionsPermissions', [{
              createdAt,
              updatedAt,
              roles_permissionsId: publicRole[0].id,
              permissionId: createLeadsPermission[0].id,
            }]);
        }
    }
  },

  down: async (queryInterface, Sequelize) => {
    // Logic to revert if needed
  }
};
