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

/**
 * Action to execute a command on a host via Real-Time Response in CrowdStrike
 */
export const executeRtrCommand = createAction({
  name: 'execute_rtr_command',
  displayName: 'Execute RTR Command',
  description: 'Execute a read-only command on a host via Real-Time Response',
  
  props: {
    session_id: Property.ShortText({
      displayName: 'Session ID',
      description: 'RTR session ID obtained from Initialize RTR Session',
      required: true,
    }),
    command_type: Property.StaticDropdown({
      displayName: 'Command Type',
      description: 'Type of command to execute',
      required: true,
      options: {
        options: [
          { label: 'Read-Only', value: RTR_COMMAND_TYPES.READ_ONLY },
          { label: 'Active Responder', value: RTR_COMMAND_TYPES.ACTIVE_RESPONDER },
        ],
      },
      defaultValue: RTR_COMMAND_TYPES.READ_ONLY,
    }),
    base_command: Property.ShortText({
      displayName: 'Base Command',
      description: 'Base command to execute (e.g., ls, cd, cat)',
      required: true,
    }),
    command_string: Property.LongText({
      displayName: 'Command String',
      description: 'Full command string including arguments',
      required: false,
    }),
  },
  
  async run(context) {
    try {
      const { auth, propsValue } = context;
      
      // Validate required parameters
      validateRequiredParams(propsValue, ['session_id', 'command_type', 'base_command']);
      
      // Determine the endpoint based on command type
      let endpoint = API_ENDPOINTS.RTR_COMMAND_EXEC;
      if (propsValue.command_type === RTR_COMMAND_TYPES.ACTIVE_RESPONDER) {
        endpoint = API_ENDPOINTS.RTR_ACTIVE_RESPONDER_COMMAND;
      }
      
      // Prepare request body
      const requestBody = {
        session_id: propsValue.session_id,
        base_command: propsValue.base_command,
        command_string: propsValue.command_string || propsValue.base_command,
      };
      
      // Make API call to execute command
      const response = await makeAuthenticatedApiCall(
        auth,
        endpoint,
        'POST',
        requestBody
      );
      
      // Check if command was executed successfully
      if (!response.resources || response.resources.length === 0) {
        throw new Error('Failed to execute RTR command');
      }
      
      const commandResult = response.resources[0];
      
      return {
        success: true,
        cloud_request_id: commandResult.cloud_request_id,
        session_id: propsValue.session_id,
        command_type: propsValue.command_type,
        base_command: propsValue.base_command,
        command_string: propsValue.command_string,
        complete: commandResult.complete || false,
        stderr: commandResult.stderr || '',
        stdout: commandResult.stdout || '',
        command_details: commandResult,
      };
    } catch (error) {
      return formatErrorResponse(error);
    }
  },
});
