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

/**
 * Action to check the status of a previously executed RTR command in CrowdStrike
 */
export const checkRtrCommandStatus = createAction({
  name: 'check_rtr_command_status',
  displayName: 'Check RTR Command Status',
  description: 'Check the status of a previously executed Real-Time Response command',
  
  props: {
    cloud_request_id: Property.ShortText({
      displayName: 'Cloud Request ID',
      description: 'Cloud request ID obtained from Execute RTR Command',
      required: true,
    }),
    session_id: Property.ShortText({
      displayName: 'Session ID',
      description: 'RTR session ID',
      required: true,
    }),
    sequence_id: Property.Number({
      displayName: 'Sequence ID',
      description: 'Sequence ID for the command (default: 0)',
      required: false,
      defaultValue: 0,
    }),
  },
  
  async run(context) {
    try {
      const { auth, propsValue } = context;
      
      // Validate required parameters
      validateRequiredParams(propsValue, ['cloud_request_id', 'session_id']);
      
      // Make API call to check command status
      const response = await makeAuthenticatedApiCall(
        auth,
        API_ENDPOINTS.RTR_COMMAND_STATUS,
        'GET',
        undefined,
        {
          cloud_request_id: propsValue.cloud_request_id,
          session_id: propsValue.session_id,
          sequence_id: (propsValue.sequence_id || 0).toString(),
        }
      );
      
      // Check if status was retrieved successfully
      if (!response.resources || response.resources.length === 0) {
        throw new Error('Failed to retrieve RTR command status');
      }
      
      const commandStatus = response.resources[0];
      
      return {
        success: true,
        cloud_request_id: propsValue.cloud_request_id,
        session_id: propsValue.session_id,
        complete: commandStatus.complete || false,
        stderr: commandStatus.stderr || '',
        stdout: commandStatus.stdout || '',
        status_details: commandStatus,
      };
    } catch (error) {
      return formatErrorResponse(error);
    }
  },
});
