import {
  Directive,
  HostListener,
  output
} from '@angular/core';

import { shouldSubmitOnEnter } from './form-field-focus.rules';

/**
 * Emits when Enter is pressed in a submittable input field.
 * Use on single-field actions or alongside native `<form ngSubmit>`.
 */
@Directive({
  selector: 'input[appSubmitOnEnter], select[appSubmitOnEnter]',
  standalone: true
})
export class SubmitOnEnterDirective {
  readonly submitOnEnter = output();

  @HostListener('keydown.enter', ['$event'])
  onEnter(event: Event): void {
    if (!(event instanceof KeyboardEvent) || !shouldSubmitOnEnter(event)) {
      return;
    }

    event.preventDefault();
    this.submitOnEnter.emit();
  }
}
