'use strict';

const { QueryTypes } = require('sequelize');

const rolePermissionMap = {
  'Director General': [
    'READ_APPROVALS',
    'READ_PROJECTS',
    'READ_CONTRACTS',
    'READ_NOTIFICATIONS',
  ],
  'Finance Director': [
    'READ_PAYMENT_REQUESTS',
    'READ_ALLOCATIONS',
    'READ_CONTRACTS',
    'READ_APPROVALS',
    'READ_NOTIFICATIONS',
  ],
  'Procurement Lead': [
    'READ_REQUISITIONS',
    'READ_TENDERS',
    'READ_VENDORS',
    'READ_VENDOR_COMPLIANCE_DOCUMENTS',
    'READ_BIDS',
    'READ_BID_EVALUATIONS',
    'READ_AWARDS',
    'READ_CONTRACTS',
    'READ_APPROVALS',
    'READ_NOTIFICATIONS',
  ],
  'Compliance and Audit Lead': [
    'READ_COMPLIANCE_ALERTS',
    'READ_AUDIT_LOGS',
    'READ_DOCUMENTS',
    'READ_APPROVALS',
    'READ_CONTRACTS',
    'READ_NOTIFICATIONS',
  ],
  'Project Delivery Lead': [
    'READ_PROJECTS',
    'READ_PROJECT_MILESTONES',
    'READ_RISKS',
    'READ_ISSUES',
    'READ_FIELD_VERIFICATIONS',
    'READ_PROGRAMS',
    'READ_PROVINCES',
    'READ_CONTRACTS',
    'READ_APPROVALS',
    'READ_PAYMENT_REQUESTS',
    'READ_NOTIFICATIONS',
  ],
};

module.exports = {
  async up(queryInterface) {
    const transaction = await queryInterface.sequelize.transaction();
    const now = new Date();

    try {
      for (const [roleName, permissionNames] of Object.entries(rolePermissionMap)) {
        const roles = await queryInterface.sequelize.query(
          'SELECT id FROM "roles" WHERE name = :roleName LIMIT 1',
          {
            replacements: { roleName },
            type: QueryTypes.SELECT,
            transaction,
          },
        );

        if (!roles[0]?.id) {
          throw new Error(`Role not found while assigning workspace permissions: ${roleName}`);
        }

        for (const permissionName of permissionNames) {
          const permissions = await queryInterface.sequelize.query(
            'SELECT id FROM "permissions" WHERE name = :permissionName LIMIT 1',
            {
              replacements: { permissionName },
              type: QueryTypes.SELECT,
              transaction,
            },
          );

          if (!permissions[0]?.id) {
            throw new Error(`Permission not found while assigning workspace permissions: ${permissionName}`);
          }

          await queryInterface.sequelize.query(
            `INSERT INTO "rolesPermissionsPermissions" ("createdAt", "updatedAt", "roles_permissionsId", "permissionId")
             VALUES (:createdAt, :updatedAt, :roleId, :permissionId)
             ON CONFLICT ("roles_permissionsId", "permissionId") DO NOTHING`,
            {
              replacements: {
                createdAt: now,
                updatedAt: now,
                roleId: roles[0].id,
                permissionId: permissions[0].id,
              },
              transaction,
            },
          );
        }
      }

      await transaction.commit();
    } catch (error) {
      await transaction.rollback();
      console.error('Error assigning workspace read permissions:', error);
      throw error;
    }
  },

  async down() {},
};
