import {
  createTrigger,
  Property,
  TriggerStrategy,
} from '@activepieces/pieces-framework';
import { phantombusterAuth } from '../common/auth';
import { agentIdDropdown } from '../common/props';
import { MarkdownVariant } from '@activepieces/pieces-framework';

export const newOutput = createTrigger({
  auth: phantombusterAuth,
  name: 'newOutput',
  displayName: 'New Output',
  description:
    'Trigger when a new output is generated by a Phantombuster agent ',
  aiMetadata: {
    description:
      'Fires when a Phantombuster agent finishes a run and posts its result to the configured webhook, representing a completed agent execution (with its exit status and result object) for the selected agent.',
  },
  props: {
    agentId: agentIdDropdown,
    markdown: Property.MarkDown({
      variant: MarkdownVariant.INFO,
      value: `## Webhook Configuration

To use this trigger, you need to configure a webhook URL in your Phantombuster agent:

### Steps to Configure:
1. Go to your Phantombuster agent page
2. Click on **Settings**
3. Select **Advanced Notification Settings**
4. Input the webhook URL in the webhook field:
\`\`\`
{{webhookUrl}}
\`\`\`

### Supported Exit Messages (Status Values):
- \`finished\` - Agent completed successfully (exitCode: 0)
- \`killed\` - Agent was killed
- \`global timeout\` - Global timeout reached
- \`org timeout\` - Organization timeout reached
- \`agent timeout\` - Agent timeout reached
- \`unknown\` - Unknown status

### Important Notes:
- Maximum webhook timeout: 11 seconds
- Webhooks accept POST requests only
- Maximum 2 redirections allowed
- Response body is ignored (you don't need to respond with data)

[Learn more about webhooks](https://hub.phantombuster.com/docs/using-webhooks)`,
    }),
  },
  sampleData: {
    agentId: '5027055349780535',
    agentName: 'Test Script',
    containerId: '3358014727012763',
    script: 'test_script_50516785467.js',
    scriptOrg: 'phantombuster',
    branch: 'test-branch-0545107204',
    launchDuration: 121,
    runDuration: 1850,
    resultObject: {},
    exitMessage: 'finished',
    exitCode: 0,
  },
  type: TriggerStrategy.WEBHOOK,
  async onEnable(context) {
    // implement webhook creation logic
  },
  async onDisable(context) {
    // implement webhook deletion logic
  },
  async run(context) {
    const output = context.payload.body as any;
    console.log(output);
    if (output.agentId != context.propsValue.agentId) {
      return [];
    }

    return [output];
  },
});
