import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';
import { outsetaAuth } from '../auth';
import { OutsetaClient } from '../common/client';

export const newAccountEventTrigger = createTrigger({
  name: 'new_account_event',
  auth: outsetaAuth,
  displayName: 'New Account Event',
  description: 'Triggers on account-scoped events (lifecycle, stage, billing, subscription, invoice).',
  type: TriggerStrategy.WEBHOOK,
  aiMetadata: {
    description:
      'Fires on any account-scoped Outseta event (account lifecycle, stage change, billing, subscription, invoice). Each webhook delivers one Account object; the specific event\'s details are nested in its ActivityEventData.',
  },
  props: {
    setup: Property.MarkDown({
      value: `
- In Outseta, go to **Settings → Notifications → Add Notification**.
- Select the account event and paste the webhook URL in the callback field:
  \`\`\`text
  {{webhookUrl}}
  \`\`\`
- Create one notification per event, all pointing to this same URL.
`,
    }),
    eventSubTypes: Property.StaticMultiSelectDropdown({
      displayName: 'Events',
      description:
        'Select one or more account-scoped events to listen for. Configure a matching Outseta notification for each, all pointing to this webhook URL.',
      required: true,
      options: {
        disabled: false,
        // Mirrors the Outseta admin dropdown verbatim (Settings → Notifications →
        // Add Notification → Activity Type), so users can match each option here
        // 1:1 with the notifications they configure on the Outseta side.
        options: [
          { label: 'Account Created', value: 'account_created' },
          { label: 'Account Updated', value: 'account_updated' },
          { label: 'Account Add Person', value: 'account_add_person' },
          { label: 'Account Remove Person', value: 'account_remove_person' },
          { label: 'Account Primary Person Updated', value: 'account_primary_person_updated' },
          { label: 'Account Stage Updated', value: 'account_stage_updated' },
          { label: 'Account Deleted', value: 'account_deleted' },
          { label: 'Account Billing Information Removed', value: 'account_billing_information_removed' },
          { label: 'Account Billing Information Requested', value: 'account_billing_information_requested' },
          { label: 'Account Billing Information Updated', value: 'account_billing_information_updated' },
          { label: 'Account Billing Invoice Email Sent', value: 'account_billing_invoice_email_sent' },
          { label: 'Account Billing Invoice Created', value: 'account_billing_invoice_created' },
          { label: 'Account Billing Invoice Deleted', value: 'account_billing_invoice_deleted' },
          { label: 'Account Paid Subscription Created', value: 'account_paid_subscription_created' },
          { label: 'Account Subscription Add Ons Changed', value: 'account_subscription_add_ons_changed' },
          { label: 'Account Subscription Cancellation Requested', value: 'account_subscription_cancellation_requested' },
          { label: 'Account Subscription Plan Updated', value: 'account_subscription_plan_updated' },
          { label: 'Account Subscription Payment Collected', value: 'account_subscription_payment_collected' },
          { label: 'Account Subscription Payment Declined', value: 'account_subscription_payment_declined' },
          { label: 'Account Subscription Renewal Extended', value: 'account_subscription_renewal_extended' },
          { label: 'Account Subscription Started', value: 'account_subscription_started' },
          // Manual activity events. Per Outseta support, these fire with the
          // entity they are attached to as the webhook payload — when logged
          // against an Account, the body is the Account.
          { label: 'Custom', value: 'custom' },
          { label: 'Note', value: 'note' },
          { label: 'Email', value: 'email' },
          { label: 'Phone Call', value: 'phone_call' },
          { label: 'Meeting', value: 'meeting' },
          { label: 'Chat', value: 'chat' },
        ],
      },
    }),
  },
  sampleData: {
    Uid: 'abc123xyz',
    Name: 'Example Corp',
    AccountStage: 2,
    AccountStageLabel: 'Subscribing',
    ClientIdentifier: null,
    InvoiceNotes: null,
    PersonAccount: [],
    Subscriptions: [],
    ActivityEventData: null,
    Created: '2024-01-10T00:00:00Z',
    Updated: '2024-01-10T00:00:00Z',
  },
  async onEnable() {
    // Webhook must be configured manually in Outseta (Settings → Notifications)
  },
  async onDisable() {
    // Webhook must be removed manually in Outseta
  },
  async run(context) {
    return [context.payload.body as Record<string, unknown>];
  },
  async test(context) {
    const client = new OutsetaClient({
      domain: context.auth.props.domain,
      apiKey: context.auth.props.apiKey,
      apiSecret: context.auth.props.apiSecret,
    });

    const selected = (context.propsValue.eventSubTypes ?? []) as string[];
    const onlyCreate = selected.length > 0 && selected.every((s) => s.endsWith('_created'));
    const orderProperty = onlyCreate ? 'Created' : 'Updated';
    const res = await client.get<{ items?: Record<string, unknown>[]; Items?: Record<string, unknown>[] }>(
      `/api/v1/crm/accounts?limit=5&orderBy=${orderProperty}%20DESC`
    );
    return res?.items ?? res?.Items ?? [];
  },
});
