import {
  Property,
  createAction,
} from '@activepieces/pieces-framework';
import { shopifyAuth } from '../..';
import { createCustomer } from '../common';

export const createCustomerAction = createAction({
  auth: shopifyAuth,
  name: 'create_customer',
  displayName: 'Create Customer',
  description: 'Create a new customer.',
  audience: 'both',
  aiMetadata: { description: 'Create a new Shopify customer record with email, name, phone, tags, and marketing consent. Pick this for a new contact; use Update Customer to edit an existing one. Each call creates a new record, so repeating it may produce duplicate customers.', idempotent: false },
  props: {
    email: Property.ShortText({
      displayName: 'Email',
      required: false,
    }),
    verifiedEmail: Property.Checkbox({
      displayName: 'Verified Email',
      description: 'Whether the customer has verified their email.',
      required: false,
      defaultValue: true,
    }),
    sendEmailInvite: Property.Checkbox({
      displayName: 'Send Email Invite',
      required: false,
      defaultValue: false,
    }),
    firstName: Property.ShortText({
      displayName: 'First Name',
      required: false,
    }),
    lastName: Property.ShortText({
      displayName: 'Last Name',
      required: false,
    }),
    phoneNumber: Property.ShortText({
      displayName: 'Phone Number',
      required: false,
    }),
    tags: Property.ShortText({
      displayName: 'Tags',
      description: 'A string of comma-separated tags for filtering and search',
      required: false,
    }),
    acceptsMarketing:Property.Checkbox({
      displayName:'Accepts Marketing ?',
      required:false
    })
  },
  async run({ auth, propsValue }) {
    const {
      email,
      verifiedEmail,
      sendEmailInvite,
      firstName,
      lastName,
      phoneNumber,
      tags,
      acceptsMarketing
    } = propsValue;

    return await createCustomer(
      {
        email,
        verified_email: verifiedEmail,
        send_email_invite: sendEmailInvite,
        first_name: firstName,
        last_name: lastName,
        phone: phoneNumber,
        tags,
        email_marketing_consent:{
          state:acceptsMarketing?'subscribed':'not_subscribed',
          opt_in_level:"unknown"
        }
      },
      auth
    );
  },
});
