import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { pinchPaymentsAuth } from '../common/auth';
import { createWebhook, deleteWebhook, WebhookResponse } from '../common/client';

export const subscriptionCompleteTrigger = createTrigger({
  auth: pinchPaymentsAuth,
  name: 'subscription_complete',
  displayName: 'Subscription Complete',
  description: 'Triggers when a subscription is run to completion',
  aiMetadata: {
    description: 'Fires when a recurring subscription reaches the end of its term and runs to completion in Pinch Payments (all scheduled payments done), as distinct from being cancelled early. Use to react when a finite billing plan finishes.',
  },
  type: TriggerStrategy.WEBHOOK,
  props: {},
  async onEnable(context) {
    const credentials = {
      username: context.auth.props.username,
      password: context.auth.props.password,
      environment: context.auth.props.environment
    };

    const webhook = await createWebhook(credentials, {
      uri: context.webhookUrl,
      webhookFormat: 'camel-case',
      eventTypes: ['subscription-complete'],
    });

    await context.store.put<WebhookResponse>('pinch_subscription_complete_webhook', webhook);
  },
  async onDisable(context) {
    const webhook = await context.store.get<WebhookResponse>('pinch_subscription_complete_webhook');
    if (webhook) {
      const credentials = {
        username: context.auth.props.username,
        password: context.auth.props.password,
        environment: context.auth.props.environment
      };
      await deleteWebhook(credentials, webhook.id);
    }
  },
  async run(context) {
    return [context.payload.body];
  },
  sampleData: {
    id: 'evt_sample123456',
    type: 'subscription-complete',
    eventDate: '2024-01-15T10:30:00Z',
    metadata: {},
    data: {
      subscription: {
        id: 'sub_sample123456',
        planId: 'pln_sample123456',
        planName: 'Monthly Plan',
        status: 'complete',
        payer: {
          id: 'pyr_sample123456',
          firstName: 'John',
          lastName: 'Doe',
          emailAddress: 'john.doe@example.com',
        },
      },
    },
  },
});
