import { createAction, Property } from '@activepieces/pieces-framework';
import { makeAuthenticatedApiCall, formatErrorResponse, validateRequiredParams } from '../../common/utils';
import { API_ENDPOINTS } from '../../common/constants';

/**
 * Action to check the isolation status of a host in CrowdStrike
 */
export const checkHostIsolationStatus = createAction({
  name: 'check_host_isolation_status',
  displayName: 'Check Host Isolation Status',
  description: 'Check the current isolation status of a host',
  
  props: {
    device_id: Property.ShortText({
      displayName: 'Device ID',
      description: 'CrowdStrike device ID to check isolation status for',
      required: true,
    }),
  },
  
  async run(context) {
    try {
      const { auth, propsValue } = context;
      
      // Validate required parameters
      validateRequiredParams(propsValue, ['device_id']);
      
      // Make API call to get device details
      const response = await makeAuthenticatedApiCall(
        auth,
        API_ENDPOINTS.DEVICES_ENTITIES,
        'GET',
        undefined,
        { ids: propsValue.device_id }
      );
      
      // Check if device exists and get isolation status
      if (!response.resources || response.resources.length === 0) {
        throw new Error(`Device with ID ${propsValue.device_id} not found`);
      }
      
      const device = response.resources[0];
      const status = device.status || 'unknown';
      const isIsolated = status === 'contained';
      
      return {
        success: true,
        device_id: propsValue.device_id,
        is_isolated: isIsolated,
        status: status,
        device_details: device,
      };
    } catch (error) {
      return formatErrorResponse(error);
    }
  },
});
