import { createAction, Property } from '@activepieces/pieces-framework';
import { mycaseAuth } from '../auth';
import { createMyCaseApi } from '../common/mycase-api';

export const findPracticeArea = createAction({
  auth: mycaseAuth,
  name: 'find_practice_area',
  displayName: 'Find Practice Area',
  description: 'Searches for practice areas with optional filters',
  audience: 'both',
  aiMetadata: { description: 'List or search MyCase practice areas, optionally filtering by last-updated date and limiting page size. Use to resolve a practice-area name to its ID or browse available practice areas. Read-only and idempotent. To add a missing practice area, use Create Practice Area.', idempotent: true },
  props: {
    updated_after: Property.DateTime({
      displayName: 'Updated After',
      description: 'Filter practice areas updated after this date and time',
      required: false,
    }),
    page_size: Property.Number({
      displayName: 'Page Size',
      description: 'Number of results per page (1-1000)',
      required: false,
      defaultValue: 25,
    }),
  },
  async run(context) {
    const api = createMyCaseApi(context.auth);
    
    const queryParams: Record<string, string> = {};
    
    if (context.propsValue.updated_after) {
      // Convert DateTime to ISO string format
      queryParams['filter[updated_after]'] = new Date(context.propsValue.updated_after).toISOString();
    }
    
    if (context.propsValue.page_size) {
      queryParams['page_size'] = context.propsValue.page_size.toString();
    }

    try {
      const response = await api.get('/practice_areas', queryParams);
      
      if (response.success) {
        return {
          success: true,
          practice_areas: response.data,
          count: Array.isArray(response.data) ? response.data.length : 0,
        };
      } else {
        return {
          success: false,
          error: response.error,
          details: response.details,
        };
      }
    } catch (error) {
      return {
        success: false,
        error: 'Failed to find practice areas',
        details: error instanceof Error ? error.message : String(error),
      };
    }
  },
});
