import { createAction, Property } from '@activepieces/pieces-framework';
import { genderApiAuth } from '../common/auth';
import { httpClient, HttpMethod } from '@activepieces/pieces-common';

export const getGenderByFirstName = createAction({
  auth: genderApiAuth,
  name: 'getGenderByFirstName',
  displayName: 'Get Gender by First Name',
  description: 'Predict the gender of a person based on their first name',
  audience: 'both',
  aiMetadata: {
    description:
      'Predicts the likely gender of a person from a single first name via the Gender API. Use when you have only a given name (not a full name); optionally pass a country code and/or locale to improve accuracy for region-specific names. Read-only lookup that is safe to repeat.',
    idempotent: true,
  },
  props: {
    first_name: Property.ShortText({
      displayName: 'First Name',
      description: 'The first name to query',
      required: true,
    }),
    country_code: Property.ShortText({
      displayName: 'Country Code',
      description: 'ISO 3166-1 alpha-2 country code to improve accuracy (e.g., "US", "DE")',
      required: false,
    }),
    locale: Property.ShortText({
      displayName: 'Locale',
      description: 'Browser locale for localization (e.g., "en-US", "de-DE")',
      required: false,
    }),
  },
  async run(context) {
    const payload: any = {
      first_name: context.propsValue.first_name,
    };

    if (context.propsValue.country_code) {
      payload.country_code = context.propsValue.country_code;
    }

    if (context.propsValue.locale) {
      payload.locale = context.propsValue.locale;
    }

    const response = await httpClient.sendRequest({
      method: HttpMethod.POST,
      url: 'https://gender-api.com/v2/gender',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${context.auth.secret_text}`,
      },
      body: payload,
    });

    return response.body;
  },
});
