'use strict';

/**
 * Adds missing store/inventory permissions and assigns them to STORE_KEEPER and STORE_ASSISTANT.
 * Run this seeder on existing databases to fix store user access to Stock Register, Transaction History, etc.
 * Safe to run multiple times (ignoreDuplicates).
 */
module.exports = {
  async up(queryInterface, Sequelize) {
    const newPermissions = [
      { permission_code: 'INVENTORY.STOCK_REGISTER.ALL', permission_name: 'Stock Register - All', module: 'INVENTORY', resource: 'stock_register', action: 'ALL', is_system_permission: true, status: 'ACTIVE', created_at: new Date(), updated_at: new Date() },
      { permission_code: 'INVENTORY.STOCK_REGISTER.READ', permission_name: 'Stock Register - Read', module: 'INVENTORY', resource: 'stock_register', action: 'READ', is_system_permission: true, status: 'ACTIVE', created_at: new Date(), updated_at: new Date() },
      { permission_code: 'INVENTORY.TRANSACTION_HISTORY.ALL', permission_name: 'Transaction History (Stock Transfer History) - All', module: 'INVENTORY', resource: 'transaction_history', action: 'ALL', is_system_permission: true, status: 'ACTIVE', created_at: new Date(), updated_at: new Date() },
      { permission_code: 'INVENTORY.TRANSACTION_HISTORY.READ', permission_name: 'Transaction History (Stock Transfer History) - Read', module: 'INVENTORY', resource: 'transaction_history', action: 'READ', is_system_permission: true, status: 'ACTIVE', created_at: new Date(), updated_at: new Date() },
      { permission_code: 'INVENTORY.BATCH_SERIAL.ALL', permission_name: 'Batch & Serial Tracking - All', module: 'INVENTORY', resource: 'batch_serial', action: 'ALL', is_system_permission: true, status: 'ACTIVE', created_at: new Date(), updated_at: new Date() },
      { permission_code: 'INVENTORY.BATCH_SERIAL.READ', permission_name: 'Batch & Serial Tracking - Read', module: 'INVENTORY', resource: 'batch_serial', action: 'READ', is_system_permission: true, status: 'ACTIVE', created_at: new Date(), updated_at: new Date() },
      { permission_code: 'MASTER.STORAGE_LOCATION.ALL', permission_name: 'Storage Location - All', module: 'MASTER', resource: 'storage_location', action: 'ALL', is_system_permission: true, status: 'ACTIVE', created_at: new Date(), updated_at: new Date() },
      { permission_code: 'MASTER.STORAGE_LOCATION.READ', permission_name: 'Storage Location - Read', module: 'MASTER', resource: 'storage_location', action: 'READ', is_system_permission: true, status: 'ACTIVE', created_at: new Date(), updated_at: new Date() },
      { permission_code: 'STORES.MATERIAL_REQUEST.ALL', permission_name: 'Stores Material Request - All', module: 'STORES', resource: 'material_request', action: 'ALL', is_system_permission: true, status: 'ACTIVE', created_at: new Date(), updated_at: new Date() },
      { permission_code: 'STORES.MATERIAL_REQUEST.CREATE', permission_name: 'Stores Material Request - Create', module: 'STORES', resource: 'material_request', action: 'CREATE', is_system_permission: true, status: 'ACTIVE', created_at: new Date(), updated_at: new Date() },
      { permission_code: 'STORES.MATERIAL_REQUEST.READ', permission_name: 'Stores Material Request - Read', module: 'STORES', resource: 'material_request', action: 'READ', is_system_permission: true, status: 'ACTIVE', created_at: new Date(), updated_at: new Date() },
      { permission_code: 'STORES.MATERIAL_ISSUE.ALL', permission_name: 'Stores Material Issue - All', module: 'STORES', resource: 'material_issue', action: 'ALL', is_system_permission: true, status: 'ACTIVE', created_at: new Date(), updated_at: new Date() },
      { permission_code: 'STORES.MATERIAL_ISSUE.CREATE', permission_name: 'Stores Material Issue - Create', module: 'STORES', resource: 'material_issue', action: 'CREATE', is_system_permission: true, status: 'ACTIVE', created_at: new Date(), updated_at: new Date() },
      { permission_code: 'STORES.MATERIAL_ISSUE.READ', permission_name: 'Stores Material Issue - Read', module: 'STORES', resource: 'material_issue', action: 'READ', is_system_permission: true, status: 'ACTIVE', created_at: new Date(), updated_at: new Date() },
      { permission_code: 'STORES.MATERIAL_RETURN.ALL', permission_name: 'Stores Material Return - All', module: 'STORES', resource: 'material_return', action: 'ALL', is_system_permission: true, status: 'ACTIVE', created_at: new Date(), updated_at: new Date() },
      { permission_code: 'STORES.MATERIAL_RETURN.CREATE', permission_name: 'Stores Material Return - Create', module: 'STORES', resource: 'material_return', action: 'CREATE', is_system_permission: true, status: 'ACTIVE', created_at: new Date(), updated_at: new Date() },
      { permission_code: 'STORES.MATERIAL_RETURN.READ', permission_name: 'Stores Material Return - Read', module: 'STORES', resource: 'material_return', action: 'READ', is_system_permission: true, status: 'ACTIVE', created_at: new Date(), updated_at: new Date() },
      { permission_code: 'STORES.PURCHASE_REQUISITION.ALL', permission_name: 'Stores Purchase Requisition - All', module: 'STORES', resource: 'purchase_requisition', action: 'ALL', is_system_permission: true, status: 'ACTIVE', created_at: new Date(), updated_at: new Date() },
      { permission_code: 'STORES.PURCHASE_REQUISITION.CREATE', permission_name: 'Stores Purchase Requisition - Create', module: 'STORES', resource: 'purchase_requisition', action: 'CREATE', is_system_permission: true, status: 'ACTIVE', created_at: new Date(), updated_at: new Date() },
      { permission_code: 'STORES.PURCHASE_REQUISITION.READ', permission_name: 'Stores Purchase Requisition - Read', module: 'STORES', resource: 'purchase_requisition', action: 'READ', is_system_permission: true, status: 'ACTIVE', created_at: new Date(), updated_at: new Date() },
    ];

    await queryInterface.bulkInsert('permission', newPermissions, { ignoreDuplicates: true });

    const permCodesStoreKeeper = ['INVENTORY.STOCK_REGISTER.ALL', 'INVENTORY.TRANSACTION_HISTORY.ALL', 'INVENTORY.BATCH_SERIAL.READ', 'STORES.MATERIAL_REQUEST.ALL', 'STORES.MATERIAL_ISSUE.ALL', 'STORES.MATERIAL_RETURN.ALL', 'STORES.PURCHASE_REQUISITION.ALL'];
    const permCodesStoreAssistant = ['INVENTORY.STOCK_REGISTER.READ', 'INVENTORY.TRANSACTION_HISTORY.READ', 'INVENTORY.BATCH_SERIAL.READ', 'STORES.MATERIAL_REQUEST.READ', 'STORES.MATERIAL_ISSUE.READ', 'STORES.MATERIAL_RETURN.READ', 'STORES.PURCHASE_REQUISITION.READ'];

    const permCodesList = permCodesStoreKeeper.concat(permCodesStoreAssistant).filter((v, i, a) => a.indexOf(v) === i).map(c => "'" + c + "'").join(', ');
    const [rolesResult, permissionsResult] = await Promise.all([
      queryInterface.sequelize.query("SELECT id, role_code FROM role WHERE role_code IN ('STORE_KEEPER', 'STORE_ASSISTANT')"),
      queryInterface.sequelize.query("SELECT id, permission_code FROM permission WHERE permission_code IN (" + permCodesList + ")")
    ]);

    const roles = rolesResult[0] || [];
    const perms = (permissionsResult[0] || []);
    const permissionMap = perms.reduce((acc, p) => { acc[p.permission_code] = p.id; return acc; }, {});

    const rolePerms = [];

    roles.filter(r => r.role_code === 'STORE_KEEPER').forEach(r => {
      permCodesStoreKeeper.forEach(permCode => {
        const permId = permissionMap[permCode];
        if (permId) rolePerms.push({ role_id: r.id, permission_id: permId, status: 'ACTIVE', created_at: new Date(), updated_at: new Date() });
      });
    });
    roles.filter(r => r.role_code === 'STORE_ASSISTANT').forEach(r => {
      permCodesStoreAssistant.forEach(permCode => {
        const permId = permissionMap[permCode];
        if (permId) rolePerms.push({ role_id: r.id, permission_id: permId, status: 'ACTIVE', created_at: new Date(), updated_at: new Date() });
      });
    });

    if (rolePerms.length > 0) {
      await queryInterface.bulkInsert('role_permission', rolePerms, { ignoreDuplicates: true });
      console.log(`Store inventory permissions: inserted ${rolePerms.length} role-permission mappings for STORE_KEEPER/STORE_ASSISTANT`);
    }
  },

  async down(queryInterface, Sequelize) {
    // Remove role_permission rows for store roles and these permission codes only
    const dialect = queryInterface.sequelize.getDialect ? queryInterface.sequelize.getDialect() : 'mysql';
    if (dialect === 'mysql' || dialect === 'mariadb') {
      await queryInterface.sequelize.query(`
        DELETE rp FROM role_permission rp
        INNER JOIN permission p ON p.id = rp.permission_id
        INNER JOIN role r ON r.id = rp.role_id
        WHERE r.role_code IN ('STORE_KEEPER', 'STORE_ASSISTANT')
        AND p.permission_code IN (
          'INVENTORY.STOCK_REGISTER.ALL', 'INVENTORY.STOCK_REGISTER.READ',
          'INVENTORY.TRANSACTION_HISTORY.ALL', 'INVENTORY.TRANSACTION_HISTORY.READ',
          'INVENTORY.BATCH_SERIAL.READ',
          'STORES.MATERIAL_REQUEST.ALL', 'STORES.MATERIAL_REQUEST.READ',
          'STORES.MATERIAL_ISSUE.ALL', 'STORES.MATERIAL_ISSUE.READ',
          'STORES.MATERIAL_RETURN.ALL', 'STORES.MATERIAL_RETURN.READ',
          'STORES.PURCHASE_REQUISITION.ALL', 'STORES.PURCHASE_REQUISITION.READ'
        )
      `);
    } else {
      await queryInterface.sequelize.query(`
        DELETE FROM role_permission WHERE id IN (
          SELECT rp.id FROM role_permission rp
          INNER JOIN permission p ON p.id = rp.permission_id
          INNER JOIN role r ON r.id = rp.role_id
          WHERE r.role_code IN ('STORE_KEEPER', 'STORE_ASSISTANT')
          AND p.permission_code IN (
            'INVENTORY.STOCK_REGISTER.ALL', 'INVENTORY.STOCK_REGISTER.READ',
            'INVENTORY.TRANSACTION_HISTORY.ALL', 'INVENTORY.TRANSACTION_HISTORY.READ',
            'INVENTORY.BATCH_SERIAL.READ'
          )
        )
      `);
    }
  }
};
