'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    // Get users and roles
    const [usersResult, rolesResult, adminUser] = await Promise.all([
      queryInterface.sequelize.query("SELECT id, username FROM user WHERE company_id IS NOT NULL AND username != 'admin'"),
      queryInterface.sequelize.query("SELECT id, role_code FROM role WHERE company_id IS NOT NULL"),
      queryInterface.sequelize.query("SELECT id FROM user WHERE username = 'admin' LIMIT 1")
    ]);

    const users = usersResult[0];
    const roles = rolesResult[0];
    const userId = adminUser[0].length > 0 ? adminUser[0][0].id : null;

    if (users.length === 0 || roles.length === 0) {
      console.log('Users or roles not found. Skipping user-role seeding.');
      return;
    }

    // Create maps
    const userMap = {};
    users.forEach(user => {
      userMap[user.username] = user.id;
    });

    const roleMap = {};
    roles.forEach(role => {
      roleMap[role.role_code] = role.id;
    });

    const userRoles = [];

    // Helper function to assign role
    const assignRole = (username, roleCode) => {
      const userId = userMap[username];
      const roleId = roleMap[roleCode];
      if (userId && roleId) {
        userRoles.push({
          user_id: userId,
          role_id: roleId,
          status: 'ACTIVE',
          created_by: userId,
          created_at: new Date(),
          updated_at: new Date()
        });
      }
    };

    // Management
    assignRole('ceo.ram', 'CEO');
    assignRole('gm.ram', 'GM');

    // Production
    assignRole('prod.mgr', 'PROD_MGR');
    assignRole('prod.sup1', 'PROD_SUPERVISOR');
    assignRole('prod.op1', 'PROD_OPERATOR');

    // Welding
    assignRole('weld.sup1', 'WELD_SUPERVISOR');
    assignRole('welder1', 'WELDER');

    // Assembly
    assignRole('assy.sup1', 'ASSY_SUPERVISOR');
    assignRole('assy.op1', 'ASSY_OPERATOR');

    // Quality
    assignRole('qa.mgr', 'QA_MGR');
    assignRole('qa.insp1', 'QA_INSPECTOR');
    assignRole('qc.insp1', 'QC_INSPECTOR');

    // Purchase
    assignRole('pur.mgr', 'PUR_MGR');
    assignRole('pur.exec1', 'PUR_EXECUTIVE');
    assignRole('pur.asst1', 'PUR_ASSISTANT');

    // Stores
    assignRole('store.keeper1', 'STORE_KEEPER');
    assignRole('store.asst1', 'STORE_ASSISTANT');

    // Sales
    assignRole('sales.mgr', 'SALES_MGR');
    assignRole('sales.exec1', 'SALES_EXECUTIVE');
    assignRole('sales.asst1', 'SALES_ASSISTANT');

    // Engineering
    assignRole('eng.mgr', 'ENG_MGR');
    assignRole('design.eng1', 'DESIGN_ENGINEER');
    assignRole('process.eng1', 'PROCESS_ENGINEER');

    // Finance
    assignRole('fin.mgr', 'FIN_MGR');
    assignRole('accountant1', 'ACCOUNTANT');
    assignRole('acc.asst1', 'ACCOUNTS_ASSISTANT');

    // HR
    assignRole('hr.mgr', 'HR_MGR');
    assignRole('hr.exec1', 'HR_EXECUTIVE');

    // IT
    assignRole('it.admin', 'IT_ADMIN');

    // Maintenance
    assignRole('maint.sup1', 'MAINT_SUPERVISOR');
    assignRole('maint.tech1', 'MAINT_TECHNICIAN');

    // Remove duplicates
    const uniqueUserRoles = [];
    const seen = new Set();
    userRoles.forEach(ur => {
      const key = `${ur.user_id}-${ur.role_id}`;
      if (!seen.has(key)) {
        seen.add(key);
        uniqueUserRoles.push(ur);
      }
    });

    await queryInterface.bulkInsert('user_role', uniqueUserRoles, {
      ignoreDuplicates: true
    });

    console.log(`Inserted ${uniqueUserRoles.length} user-role assignments`);
  },

  async down(queryInterface, Sequelize) {
    await queryInterface.bulkDelete('user_role', null, {});
  }
};

