import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import {
  HttpMethod,
  AuthenticationType,
  httpClient,
} from '@activepieces/pieces-common';
import { lobstermailCommon, inboxIdDropdownOptional } from '../common';
import { lobstermailAuth } from '../..';

export const newEmailTrigger = createTrigger({
  auth: lobstermailAuth,
  name: 'new_email',
  displayName: 'New Email Received',
  description: 'Triggers instantly when a new email is received in an inbox.',
  aiMetadata: {
    description: 'Fires via webhook the moment an inbound email arrives, optionally scoped to a single inbox. Each event represents one received message with sender, recipients, subject, preview, thread id, and an injection-risk score; fetch the full body with Get Email.',
  },
  type: TriggerStrategy.WEBHOOK,
  props: {
    inbox_id: inboxIdDropdownOptional,
  },
  sampleData: {
    event: 'email.received',
    email_id: 'eml_sample123',
    inbox_id: 'ibx_sample456',
    from: 'sender@example.com',
    to: 'you@lobstermail.ai',
    subject: 'Hello from LobsterMail',
    preview: 'This is a sample email body.',
    thread_id: null,
    injection_risk_score: 0,
    received_at: '2026-01-01T00:00:00.000Z',
  },

  async onEnable(context) {
    const body: Record<string, unknown> = {
      url: context.webhookUrl,
      events: ['email.received'],
    };
    if (context.propsValue.inbox_id) {
      body['inboxId'] = context.propsValue.inbox_id;
    }

    const response = await httpClient.sendRequest<{
      id: string;
      secret: string;
    }>({
      method: HttpMethod.POST,
      url: `${lobstermailCommon.baseUrl}/v1/webhooks`,
      body,
      authentication: {
        type: AuthenticationType.BEARER_TOKEN,
        token: context.auth.secret_text,
      },
    });

    await context.store.put('webhookId', response.body.id);
  },

  async onDisable(context) {
    const webhookId = await context.store.get<string>('webhookId');
    if (webhookId) {
      await httpClient.sendRequest({
        method: HttpMethod.DELETE,
        url: `${lobstermailCommon.baseUrl}/v1/webhooks/${webhookId}`,
        authentication: {
          type: AuthenticationType.BEARER_TOKEN,
          token: context.auth.secret_text,
        },
      });
    }
  },

  async run(context) {
    const payload = context.payload.body as {
      event: string;
      timestamp: string;
      data: {
        id?: string;
        inboxId?: string;
        sender?: string;
        recipients?: string[];
        subject?: string;
        preview?: string;
        threadId?: string;
        injectionRiskScore?: number;
        receivedAt?: string;
      };
    };

    const data = payload.data ?? {};
    if (payload.event !== 'email.received') {
      return [];
    }
    return [
      {
        event: payload.event,
        email_id: data.id ?? null,
        inbox_id: data.inboxId ?? null,
        from: data.sender ?? null,
        to: Array.isArray(data.recipients)
          ? data.recipients.join(', ')
          : data.recipients ?? null,
        subject: data.subject ?? null,
        preview: data.preview ?? null,
        thread_id: data.threadId ?? null,
        injection_risk_score: data.injectionRiskScore ?? null,
        received_at: data.receivedAt ?? payload.timestamp ?? null,
      },
    ];
  },
});
