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

/**
 * Action to update incidents in CrowdStrike
 */
export const updateIncidents = createAction({
  name: 'update_incidents',
  displayName: 'Update Incidents',
  description: 'Perform actions on incidents such as status updates, assignment, or tagging',
  
  props: {
    incident_ids: Property.Array({
      displayName: 'Incident IDs',
      description: 'List of incident IDs to update',
      required: true,
    }),
    status: Property.StaticDropdown({
      displayName: 'Status',
      description: 'New status for the incidents',
      required: false,
      options: {
        options: [
          { label: 'New', value: 'new' },
          { label: 'In Progress', value: 'in_progress' },
          { label: 'Closed', value: 'closed' },
          { label: 'Reopened', value: 'reopened' },
        ],
      },
    }),
    assigned_to_uuid: Property.ShortText({
      displayName: 'Assign To',
      description: 'UUID of the user to assign the incidents to',
      required: false,
    }),
    comment: Property.LongText({
      displayName: 'Comment',
      description: 'Comment to add to the incidents',
      required: false,
    }),
    tags: Property.Array({
      displayName: 'Tags',
      description: 'Tags to add to the incidents',
      required: false,
    }),
  },
  
  async run(context) {
    try {
      const { auth, propsValue } = context;
      
      // Validate required parameters
      validateRequiredParams(propsValue, ['incident_ids']);
      
      if (!Array.isArray(propsValue.incident_ids) || propsValue.incident_ids.length === 0) {
        throw new Error('At least one incident ID must be provided');
      }
      
      // Prepare request body
      const requestBody: Record<string, any> = {
        ids: propsValue.incident_ids
      };
      
      // Add optional parameters if provided
      if (propsValue.status) requestBody.status = propsValue.status;
      if (propsValue.assigned_to_uuid) requestBody.assigned_to_uuid = propsValue.assigned_to_uuid;
      if (propsValue.comment) requestBody.comment = propsValue.comment;
      if (propsValue.tags) requestBody.tags = propsValue.tags;
      
      // Make API call to update incidents
      const response = await makeAuthenticatedApiCall(
        auth,
        API_ENDPOINTS.INCIDENTS_ACTIONS,
        'POST',
        requestBody
      );
      
      return {
        success: true,
        updated_incident_ids: response.resources || [],
        meta: response.meta || {},
      };
    } catch (error) {
      return formatErrorResponse(error);
    }
  },
});
