'use strict';

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

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

    if (roles.length === 0 || permissions.length === 0) {
      console.log('Roles or permissions not found. Skipping role-permission seeding.');
      return;
    }

    // Create permission map
    const permissionMap = {};
    permissions.forEach(perm => {
      permissionMap[perm.permission_code] = perm.id;
    });

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

    const rolePermissions = [];

    // Helper function to add permissions
    const addPermissions = (roleCode, permissionCodes) => {
      const roleId = roleMap[roleCode];
      if (!roleId) return;
      
      permissionCodes.forEach(permCode => {
        const permId = permissionMap[permCode];
        if (permId) {
          rolePermissions.push({
            role_id: roleId,
            permission_id: permId,
            status: 'ACTIVE',
            created_by: userId,
            created_at: new Date(),
            updated_at: new Date()
          });
        }
      });
    };

    // CEO - All permissions
    addPermissions('CEO', permissions.map(p => p.permission_code));

    // General Manager - All except admin
    addPermissions('GM', permissions
      .filter(p => !p.permission_code.startsWith('ADMIN.'))
      .map(p => p.permission_code));

    // Production Manager - Production Planning and Production (BOM, Routing, etc.) only
    addPermissions('PROD_MGR', [
      'MASTER.BOM.ALL', 'MASTER.ROUTING.ALL', 'MASTER.WORK_CENTER.ALL', 'MASTER.MACHINE.ALL',
      'PRODUCTION.PRODUCTION_ORDER.ALL', 'PRODUCTION.MATERIAL_ISSUE.ALL',
      'PRODUCTION.PRODUCTION_CONFIRMATION.ALL', 'PRODUCTION.WIP_TRACKING.ALL',
      'PRODUCTION.SCRAP_REPORTING.ALL', 'PRODUCTION.JOB_CARD.ALL', 'PRODUCTION.WIP_BY_OPERATION.ALL',
      'PRODUCTION.MRP.ALL', 'PRODUCTION.STOCK_REGISTER.ALL',
      'INVENTORY.GOODS_ISSUE.READ', 'INVENTORY.STOCK_VIEW.READ',
      'MASTER.DEPARTMENT.READ', 'MASTER.PLANT.READ'
    ]);

    // Production Supervisor
    addPermissions('PROD_SUPERVISOR', [
      'DASHBOARD.VIEW',
      'MASTER.MATERIAL.READ', 'MASTER.BOM.READ', 'MASTER.ROUTING.READ',
      'PRODUCTION.PRODUCTION_ORDER.READ', 'PRODUCTION.PRODUCTION_ORDER.CREATE',
      'PRODUCTION.MATERIAL_ISSUE.ALL', 'PRODUCTION.PRODUCTION_CONFIRMATION.ALL',
      'PRODUCTION.WIP_TRACKING.READ', 'PRODUCTION.SCRAP_REPORTING.CREATE',
      'PRODUCTION.JOB_CARD.ALL', 'PRODUCTION.WIP_BY_OPERATION.VIEW',
      'INVENTORY.GOODS_ISSUE.READ', 'INVENTORY.STOCK_VIEW.READ'
    ]);

    // Production Operator
    addPermissions('PROD_OPERATOR', [
      'DASHBOARD.VIEW',
      'PRODUCTION.PRODUCTION_ORDER.READ', 'PRODUCTION.PRODUCTION_CONFIRMATION.CREATE',
      'PRODUCTION.WIP_TRACKING.READ', 'PRODUCTION.SCRAP_REPORTING.CREATE',
      'PRODUCTION.JOB_CARD.VIEW', 'PRODUCTION.WIP_BY_OPERATION.VIEW',
      'MASTER.MATERIAL.READ'
    ]);

    // Welding Supervisor
    addPermissions('WELD_SUPERVISOR', [
      'DASHBOARD.VIEW',
      'MASTER.MATERIAL.READ', 'MASTER.BOM.READ',
      'PRODUCTION.PRODUCTION_ORDER.READ', 'PRODUCTION.PRODUCTION_CONFIRMATION.ALL',
      'PRODUCTION.WIP_TRACKING.READ', 'PRODUCTION.SCRAP_REPORTING.CREATE',
      'PRODUCTION.JOB_CARD.ALL', 'PRODUCTION.WIP_BY_OPERATION.VIEW',
      'INVENTORY.GOODS_ISSUE.READ'
    ]);

    // Welder
    addPermissions('WELDER', [
      'DASHBOARD.VIEW',
      'PRODUCTION.PRODUCTION_ORDER.READ', 'PRODUCTION.PRODUCTION_CONFIRMATION.CREATE',
      'PRODUCTION.SCRAP_REPORTING.CREATE', 'PRODUCTION.JOB_CARD.VIEW', 'PRODUCTION.WIP_BY_OPERATION.VIEW',
      'MASTER.MATERIAL.READ'
    ]);

    // Assembly Supervisor
    addPermissions('ASSY_SUPERVISOR', [
      'DASHBOARD.VIEW',
      'MASTER.MATERIAL.READ', 'MASTER.BOM.READ',
      'PRODUCTION.PRODUCTION_ORDER.READ', 'PRODUCTION.PRODUCTION_CONFIRMATION.ALL',
      'PRODUCTION.WIP_TRACKING.READ', 'PRODUCTION.SCRAP_REPORTING.CREATE',
      'PRODUCTION.JOB_CARD.ALL', 'PRODUCTION.WIP_BY_OPERATION.VIEW',
      'INVENTORY.GOODS_ISSUE.READ'
    ]);

    // Assembly Operator
    addPermissions('ASSY_OPERATOR', [
      'DASHBOARD.VIEW',
      'PRODUCTION.PRODUCTION_ORDER.READ', 'PRODUCTION.PRODUCTION_CONFIRMATION.CREATE',
      'PRODUCTION.SCRAP_REPORTING.CREATE', 'PRODUCTION.JOB_CARD.VIEW', 'PRODUCTION.WIP_BY_OPERATION.VIEW',
      'MASTER.MATERIAL.READ'
    ]);

    // QA Manager
    addPermissions('QA_MGR', [
      'DASHBOARD.VIEW',
      'MASTER.MATERIAL.ALL', 'MASTER.DOCUMENT.ALL',
      'PURCHASE.GATE_ENTRY.QC_APPROVE', 'PURCHASE.GRN.READ',
      'PRODUCTION.PRODUCTION_ORDER.READ', 'PRODUCTION.WIP_TRACKING.READ',
      'INVENTORY.STOCK_VIEW.READ'
    ]);

    // QA Inspector
    addPermissions('QA_INSPECTOR', [
      'DASHBOARD.VIEW',
      'MASTER.MATERIAL.READ', 'MASTER.DOCUMENT.READ',
      'PURCHASE.GATE_ENTRY.QC_APPROVE', 'PURCHASE.GRN.READ',
      'PRODUCTION.PRODUCTION_ORDER.READ', 'PRODUCTION.WIP_TRACKING.READ'
    ]);

    // QC Inspector
    addPermissions('QC_INSPECTOR', [
      'DASHBOARD.VIEW',
      'MASTER.MATERIAL.READ', 'MASTER.DOCUMENT.READ',
      'PURCHASE.GATE_ENTRY.QC_APPROVE', 'PURCHASE.GRN.READ',
      'PRODUCTION.PRODUCTION_ORDER.READ'
    ]);

    // Purchase Manager
    addPermissions('PUR_MGR', [
      'DASHBOARD.VIEW',
      'MASTER.BUSINESS_PARTNER.ALL', 'MASTER.MATERIAL.READ',
      'PURCHASE.PURCHASE_REQUISITION.ALL', 'PURCHASE.REQUEST_FOR_QUOTATION.ALL',
      'PURCHASE.PURCHASE_ORDER.ALL', 'PURCHASE.GATE_ENTRY.READ',
      'PURCHASE.GRN.READ', 'PURCHASE.VENDOR_INVOICE.READ',
      'INVENTORY.STOCK_VIEW.READ'
    ]);

    // Purchase Executive
    addPermissions('PUR_EXECUTIVE', [
      'DASHBOARD.VIEW',
      'MASTER.BUSINESS_PARTNER.READ', 'MASTER.MATERIAL.READ',
      'PURCHASE.PURCHASE_REQUISITION.CREATE', 'PURCHASE.PURCHASE_REQUISITION.READ',
      'PURCHASE.REQUEST_FOR_QUOTATION.ALL', 'PURCHASE.PURCHASE_ORDER.CREATE',
      'PURCHASE.PURCHASE_ORDER.READ', 'PURCHASE.GATE_ENTRY.READ',
      'PURCHASE.GRN.READ', 'INVENTORY.STOCK_VIEW.READ'
    ]);

    // Purchase Assistant
    addPermissions('PUR_ASSISTANT', [
      'DASHBOARD.VIEW',
      'MASTER.BUSINESS_PARTNER.READ', 'MASTER.MATERIAL.READ',
      'PURCHASE.PURCHASE_REQUISITION.READ', 'PURCHASE.PURCHASE_ORDER.READ',
      'PURCHASE.GATE_ENTRY.READ', 'PURCHASE.GRN.READ'
    ]);

    // Store Keeper (no PURCHASE.* - store users use Stores > Purchase Requisition only; Purchase menu is for purchase dept)
    addPermissions('STORE_KEEPER', [
      'DASHBOARD.VIEW',
      'MASTER.MATERIAL.READ', 'MASTER.STORAGE_LOCATION.ALL',
      'STORES.MATERIAL_REQUEST.ALL', 'STORES.MATERIAL_ISSUE.ALL', 'STORES.MATERIAL_RETURN.ALL', 'STORES.PURCHASE_REQUISITION.ALL',
      'INVENTORY.GOODS_RECEIPT.ALL', 'INVENTORY.GOODS_ISSUE.ALL',
      'INVENTORY.STOCK_TRANSFER.ALL', 'INVENTORY.STOCK_ADJUSTMENT.ALL',
      'INVENTORY.STOCK_VIEW.READ', 'INVENTORY.STOCK_REGISTER.ALL', 'INVENTORY.TRANSACTION_HISTORY.ALL',
      'INVENTORY.BATCH_SERIAL.READ',
      'PRODUCTION.MATERIAL_ISSUE.READ'
    ]);

    // Store Assistant
    addPermissions('STORE_ASSISTANT', [
      'DASHBOARD.VIEW',
      'MASTER.MATERIAL.READ',
      'STORES.MATERIAL_REQUEST.READ', 'STORES.MATERIAL_ISSUE.READ', 'STORES.MATERIAL_RETURN.READ', 'STORES.PURCHASE_REQUISITION.READ',
      'INVENTORY.GOODS_RECEIPT.CREATE', 'INVENTORY.GOODS_RECEIPT.READ',
      'INVENTORY.GOODS_ISSUE.CREATE', 'INVENTORY.GOODS_ISSUE.READ',
      'INVENTORY.STOCK_VIEW.READ', 'INVENTORY.STOCK_REGISTER.READ', 'INVENTORY.TRANSACTION_HISTORY.READ',
      'INVENTORY.BATCH_SERIAL.READ'
    ]);

    // Sales Manager
    addPermissions('SALES_MGR', [
      'DASHBOARD.VIEW',
      'MASTER.BUSINESS_PARTNER.ALL', 'MASTER.MATERIAL.READ',
      'SALES.SALES_QUOTATION.ALL', 'SALES.SALES_ORDER.ALL',
      'SALES.DELIVERY.ALL', 'SALES.SALES_INVOICE.ALL',
      'CUSTOMER.CUSTOMER_QUOTATION.ALL', 'CUSTOMER.CUSTOMER_PO.ALL',
      'INVENTORY.STOCK_VIEW.READ'
    ]);

    // Sales Executive
    addPermissions('SALES_EXECUTIVE', [
      'DASHBOARD.VIEW',
      'MASTER.BUSINESS_PARTNER.READ', 'MASTER.MATERIAL.READ',
      'SALES.SALES_QUOTATION.CREATE', 'SALES.SALES_QUOTATION.READ',
      'SALES.SALES_ORDER.CREATE', 'SALES.SALES_ORDER.READ',
      'SALES.DELIVERY.CREATE', 'SALES.DELIVERY.READ',
      'CUSTOMER.CUSTOMER_QUOTATION.ALL', 'CUSTOMER.CUSTOMER_PO.ALL',
      'INVENTORY.STOCK_VIEW.READ'
    ]);

    // Sales Assistant
    addPermissions('SALES_ASSISTANT', [
      'DASHBOARD.VIEW',
      'MASTER.BUSINESS_PARTNER.READ', 'MASTER.MATERIAL.READ',
      'SALES.SALES_QUOTATION.READ', 'SALES.SALES_ORDER.READ',
      'SALES.DELIVERY.READ', 'CUSTOMER.CUSTOMER_QUOTATION.READ',
      'CUSTOMER.CUSTOMER_PO.READ'
    ]);

    // Engineering Manager
    addPermissions('ENG_MGR', [
      'DASHBOARD.VIEW',
      'MASTER.MATERIAL.ALL', 'MASTER.MATERIAL_TYPE.ALL', 'MASTER.MATERIAL_GROUP.ALL',
      'MASTER.BOM.ALL', 'MASTER.ROUTING.ALL', 'MASTER.WORK_CENTER.ALL',
      'MASTER.MACHINE.ALL', 'MASTER.DOCUMENT.ALL',
      'PRODUCTION.PRODUCTION_ORDER.READ', 'PRODUCTION.WIP_TRACKING.READ'
    ]);

    // Design Engineer
    addPermissions('DESIGN_ENGINEER', [
      'DASHBOARD.VIEW',
      'MASTER.MATERIAL.READ', 'MASTER.MATERIAL.CREATE', 'MASTER.MATERIAL.UPDATE',
      'MASTER.BOM.ALL', 'MASTER.ROUTING.ALL', 'MASTER.DOCUMENT.ALL',
      'PRODUCTION.PRODUCTION_ORDER.READ'
    ]);

    // Process Engineer
    addPermissions('PROCESS_ENGINEER', [
      'DASHBOARD.VIEW',
      'MASTER.MATERIAL.READ', 'MASTER.BOM.READ', 'MASTER.ROUTING.ALL',
      'MASTER.WORK_CENTER.ALL', 'MASTER.MACHINE.READ',
      'PRODUCTION.PRODUCTION_ORDER.READ', 'PRODUCTION.WIP_TRACKING.READ'
    ]);

    // Finance Manager
    addPermissions('FIN_MGR', [
      'DASHBOARD.VIEW',
      'MASTER.GL_ACCOUNT.ALL', 'MASTER.COST_CENTER.ALL', 'MASTER.TAX_MASTER.ALL',
      'FINANCE.ACCOUNTING_DOCUMENT.ALL', 'FINANCE.TRIAL_BALANCE.READ',
      'PURCHASE.VENDOR_INVOICE.ALL', 'SALES.SALES_INVOICE.ALL',
      'INVENTORY.STOCK_VIEW.READ'
    ]);

    // Accountant
    addPermissions('ACCOUNTANT', [
      'DASHBOARD.VIEW',
      'MASTER.GL_ACCOUNT.READ', 'MASTER.COST_CENTER.READ',
      'FINANCE.ACCOUNTING_DOCUMENT.CREATE', 'FINANCE.ACCOUNTING_DOCUMENT.READ',
      'FINANCE.TRIAL_BALANCE.READ', 'PURCHASE.VENDOR_INVOICE.READ',
      'SALES.SALES_INVOICE.READ'
    ]);

    // Accounts Assistant
    addPermissions('ACCOUNTS_ASSISTANT', [
      'DASHBOARD.VIEW',
      'MASTER.GL_ACCOUNT.READ', 'FINANCE.ACCOUNTING_DOCUMENT.READ',
      'PURCHASE.VENDOR_INVOICE.READ', 'SALES.SALES_INVOICE.READ'
    ]);

    // HR Manager
    addPermissions('HR_MGR', [
      'DASHBOARD.VIEW',
      'MASTER.ORGANIZATION.VIEW', 'MASTER.DEPARTMENT.ALL', 'MASTER.EMPLOYEE.ALL',
      'HR.EMPLOYEE.ALL', 'HR.ATTENDANCE.ALL', 'HR.PAYROLL.ALL'
    ]);

    // HR Executive
    addPermissions('HR_EXECUTIVE', [
      'DASHBOARD.VIEW',
      'MASTER.DEPARTMENT.READ', 'MASTER.EMPLOYEE.READ',
      'HR.EMPLOYEE.READ', 'HR.ATTENDANCE.ALL', 'HR.PAYROLL.READ'
    ]);

    // HR Assistant
    addPermissions('HR_ASSISTANT', [
      'DASHBOARD.VIEW',
      'MASTER.EMPLOYEE.READ', 'HR.EMPLOYEE.READ',
      'HR.ATTENDANCE.CREATE', 'HR.ATTENDANCE.READ'
    ]);

    // IT Admin
    addPermissions('IT_ADMIN', [
      'DASHBOARD.VIEW',
      'ADMIN.USER.ALL', 'ADMIN.ROLE.ALL', 'ADMIN.PERMISSION.ALL',
      'ADMIN.APPROVAL_MASTER.ALL', 'MASTER.ORGANIZATION.VIEW', 'MASTER.COMPANY.READ', 'MASTER.PLANT.READ'
    ]);

    // Maintenance Supervisor
    addPermissions('MAINT_SUPERVISOR', [
      'DASHBOARD.VIEW',
      'MASTER.MACHINE.ALL', 'MASTER.DOCUMENT.READ',
      'PRODUCTION.PRODUCTION_ORDER.READ'
    ]);

    // Maintenance Technician
    addPermissions('MAINT_TECHNICIAN', [
      'DASHBOARD.VIEW',
      'MASTER.MACHINE.READ', 'MASTER.DOCUMENT.READ'
    ]);

    // Remove duplicates
    const uniqueRolePermissions = [];
    const seen = new Set();
    rolePermissions.forEach(rp => {
      const key = `${rp.role_id}-${rp.permission_id}`;
      if (!seen.has(key)) {
        seen.add(key);
        uniqueRolePermissions.push(rp);
      }
    });

    await queryInterface.bulkInsert('role_permission', uniqueRolePermissions, {
      ignoreDuplicates: true
    });

    console.log(`Inserted ${uniqueRolePermissions.length} role-permission mappings`);
  },

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

