import { Action, type ActionSchema } from './Action.js'
import { observed, toRaw } from '../../decorators/observed.js'

/**
 * Enables keyword-based search across specified fields.
 * Endpoint: GET /[entity-collection-name]/search
 */
export interface SearchActionSchema extends ActionSchema {
  kind: 'search'
  /**
   * The fields within the entity to be included in the search scope.
   * Must be "indexable" and typically text-based.
   */
  fields: string[]
}

/**
 * Enables keyword-based search across specified fields.
 * Endpoint: GET /[entity-collection-name]/search
 */
export class SearchAction extends Action implements SearchActionSchema {
  @observed() override accessor kind: 'search'
  @observed({ deep: true }) accessor fields: string[]

  constructor(state: Partial<SearchActionSchema> = {}) {
    super(state)
    this.kind = 'search'
    this.fields = state.fields ? [...state.fields] : []
  }

  override toJSON(): SearchActionSchema {
    return {
      ...(super.toJSON() as SearchActionSchema),
      kind: 'search',
      fields: structuredClone(toRaw(this, this.fields)) as string[],
    }
  }

  static isSearchActionSchema(schema: ActionSchema): schema is SearchActionSchema {
    return schema.kind === 'search'
  }

  static isSearchAction(action: Action): action is SearchAction {
    return action.kind === 'search'
  }
}
