/**
 * 种子数据: initial_data
 * 创建时间: 2023-01-01T00:00:00.000Z
 * 描述: 初始化基础数据
 */
'use strict';
const bcrypt = require('bcryptjs');

module.exports = {
  up: async (queryInterface, Sequelize) => {
    // 插入基础角色数据
    await queryInterface.bulkInsert('roles', [
      {
        name: 'admin',
        description: '系统管理员',
        created_at: new Date()
      },
      {
        name: 'user',
        description: '普通用户',
        created_at: new Date()
      },
      {
        name: 'guest',
        description: '访客',
        created_at: new Date()
      }
    ]);

    // 生成密码哈希
    const passwordHash = await bcrypt.hash('123456', 10);

    // 插入示例用户数据
    await queryInterface.bulkInsert('users', [
      {
        username: 'admin',
        email: 'admin@example.com',
        password: passwordHash,
        created_at: new Date(),
        updated_at: new Date()
      },
      {
        username: 'john_doe',
        email: 'john@example.com',
        password: passwordHash,
        created_at: new Date(),
        updated_at: new Date()
      }
    ]);

    // 获取用户和角色的ID
    const users = await queryInterface.sequelize.query(
      'SELECT id, username FROM users',
      { type: Sequelize.QueryTypes.SELECT }
    );

    const roles = await queryInterface.sequelize.query(
      'SELECT id, name FROM roles',
      { type: Sequelize.QueryTypes.SELECT }
    );

    const adminUser = users.find(user => user.username === 'admin');
    const johnUser = users.find(user => user.username === 'john_doe');
    const adminRole = roles.find(role => role.name === 'admin');
    const userRole = roles.find(role => role.name === 'user');

    // 为用户分配角色
    if (adminUser && adminRole) {
      await queryInterface.bulkInsert('user_roles', [{
        user_id: adminUser.id,
        role_id: adminRole.id,
        assigned_at: new Date()
      }]);
    }

    if (johnUser && userRole) {
      await queryInterface.bulkInsert('user_roles', [{
        user_id: johnUser.id,
        role_id: userRole.id,
        assigned_at: new Date()
      }]);
    }

    // 插入示例产品数据
    await queryInterface.bulkInsert('products', [
      {
        name: '示例产品1',
        description: '这是一个示例产品',
        price: 99.99,
        stock: 100,
        status: 'active',
        created_at: new Date(),
        updated_at: new Date()
      },
      {
        name: '示例产品2',
        description: '这是另一个示例产品',
        price: 149.99,
        stock: 50,
        status: 'active',
        created_at: new Date(),
        updated_at: new Date()
      }
    ]);
  },

  down: async (queryInterface, Sequelize) => {
    // 按照依赖关系的相反顺序删除数据
    await queryInterface.bulkDelete('user_roles', null, {});
    await queryInterface.bulkDelete('products', null, {});
    await queryInterface.bulkDelete('users', null, {});
    await queryInterface.bulkDelete('roles', null, {});
  }
};