/ opencodehub / src / lib / automations.ts
swadhinbiswas feat: implement air-gapped mode, UI fixes, and project management integrations · 7/9/2026
e3bd4a1
902 lines · 26.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
/**
 * Automations Engine Library
 * Workflow automation with triggers, conditions, and actions
 */

import { getDatabase, schema } from "@/db";
import type {
  AutomationAction,
  AutomationCondition,
  AutomationTrigger,
} from "@/db/schema/automations";
import { logger } from "@/lib/logger";
import { and, desc, eq } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { generateId } from "./utils";

const RETRYABLE_ACTIONS = new Set<AutomationAction["type"]>([
  "notify_slack",
  "notify_discord",
  "notify_teams",
  "trigger_ai_review",
  "trigger_iac_hook",
  "trigger_cloud_deploy",
]);

const DEFAULT_MAX_ATTEMPTS = 1;
const DEFAULT_RETRYABLE_MAX_ATTEMPTS = 3;

function sleep(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

function getMaxAttemptsForAction(action: AutomationAction): number {
  const requested = Number(action.params.maxAttempts);
  if (Number.isInteger(requested) && requested >= 1 && requested <= 5) {
    return requested;
  }
  return RETRYABLE_ACTIONS.has(action.type)
    ? DEFAULT_RETRYABLE_MAX_ATTEMPTS
    : DEFAULT_MAX_ATTEMPTS;
}

async function recordDeadLetterExecution(options: {
  ruleId: string;
  executionId: string;
  repositoryId?: string | null;
  triggeredById?: string;
  triggeredByType: string;
  triggerEvent: string;
  errorMessage: string;
  actionType?: string;
}) {
  try {
    const db = getDatabase() as NodePgDatabase<typeof schema>;
    await db.insert(schema.auditLogs).values({
      id: generateId(),
      userId: null,
      repositoryId: options.repositoryId || null,
      organizationId: null,
      action: "automation.dead_letter",
      actorType: "system",
      actorId: "automation-engine",
      targetType: "automation_execution",
      targetId: options.executionId,
      targetName: options.ruleId,
      data: JSON.stringify({
        ruleId: options.ruleId,
        executionId: options.executionId,
        triggeredById: options.triggeredById,
        triggeredByType: options.triggeredByType,
        triggerEvent: options.triggerEvent,
        actionType: options.actionType || null,
        errorMessage: options.errorMessage,
        deadLetteredAt: new Date().toISOString(),
      }),
      createdAt: new Date(),
    });
  } catch (error) {
    logger.error(
      {
        error: error instanceof Error ? error.message : "Unknown error",
        executionId: options.executionId,
      },
      "Failed to record automation dead-letter audit log",
    );
  }
}

/**
 * Trigger an automation event
 * This is the main entry point for automation processing
 */
export async function triggerAutomation(
  repositoryId: string,
  event: AutomationTrigger,
  context: {
    pullRequestId?: string;
    issueId?: string;
    labelName?: string;
    userId?: string;
    metadata?: Record<string, unknown>;
  },
) {
  const db = getDatabase() as NodePgDatabase<typeof schema>;
  const startTime = Date.now();

  try {
    // Get all enabled rules for this trigger
    const rules = await db.query.automationRules.findMany({
      where: and(
        eq(schema.automationRules.repositoryId, repositoryId),
        eq(schema.automationRules.trigger, event),
        eq(schema.automationRules.isEnabled, true),
      ),
      orderBy: [desc(schema.automationRules.priority)],
    });

    if (rules.length === 0) {
      return { triggered: 0, executed: 0 };
    }

    let executed = 0;

    for (const rule of rules) {
      const executionId = generateId();

      try {
        // Check conditions
        const conditions = rule.conditions
          ? (JSON.parse(rule.conditions) as AutomationCondition[])
          : [];
        const conditionsMatched = await evaluateConditions(conditions, context);

        // Log execution start
        await db.insert(schema.automationExecutions).values({
          id: executionId,
          ruleId: rule.id,
          triggeredById: context.pullRequestId || context.issueId,
          triggeredByType: context.pullRequestId
            ? "pull_request"
            : context.issueId
              ? "issue"
              : "other",
          triggerEvent: event,
          conditionsMatched,
          status: "pending",
          createdAt: new Date(),
        });

        if (!conditionsMatched) {
          await db
            .update(schema.automationExecutions)
            .set({ status: "skipped" })
            .where(eq(schema.automationExecutions.id, executionId));
          continue;
        }

        // Execute actions
        const actions = JSON.parse(rule.actions) as AutomationAction[];
        const executedActions: Array<{
          type: string;
          status: "success" | "failed";
          attempts: number;
          error?: string;
        }> = [];

        for (const action of actions) {
          const maxAttempts = getMaxAttemptsForAction(action);
          let lastError: Error | null = null;
          let attempts = 0;

          for (let attempt = 1; attempt <= maxAttempts; attempt++) {
            attempts = attempt;
            try {
              await executeAction(action, context);
              lastError = null;
              break;
            } catch (error) {
              lastError =
                error instanceof Error
                  ? error
                  : new Error("Unknown action execution error");
              const isLastAttempt = attempt === maxAttempts;
              if (!isLastAttempt) {
                // Small bounded backoff to improve external API reliability without stalling workers.
                await sleep(25 * attempt);
              }
            }
          }

          if (lastError) {
            executedActions.push({
              type: action.type,
              status: "failed",
              attempts,
              error: lastError.message,
            });

            await recordDeadLetterExecution({
              ruleId: rule.id,
              executionId,
              repositoryId: rule.repositoryId,
              triggeredById: context.pullRequestId || context.issueId,
              triggeredByType: context.pullRequestId
                ? "pull_request"
                : context.issueId
                  ? "issue"
                  : "other",
              triggerEvent: event,
              errorMessage: lastError.message,
              actionType: action.type,
            });

            throw lastError;
          }

          executedActions.push({
            type: action.type,
            status: "success",
            attempts,
          });
        }

        // Update execution record
        const durationMs = Date.now() - startTime;
        await db
          .update(schema.automationExecutions)
          .set({
            status: "success",
            actionsExecuted: JSON.stringify(executedActions),
            durationMs,
          })
          .where(eq(schema.automationExecutions.id, executionId));

        // Update rule stats
        await db
          .update(schema.automationRules)
          .set({
            runCount: (rule.runCount || 0) + 1,
            lastRunAt: new Date(),
          })
          .where(eq(schema.automationRules.id, rule.id));

        executed++;
      } catch (error) {
        logger.error("Automation execution failed", {
          ruleId: rule.id,
          error: error instanceof Error ? error.message : "Unknown error",
        });

        await db
          .update(schema.automationExecutions)
          .set({
            status: "failed",
            errorMessage:
              error instanceof Error ? error.message : "Unknown error",
            durationMs: Date.now() - startTime,
          })
          .where(eq(schema.automationExecutions.id, executionId));

        await recordDeadLetterExecution({
          ruleId: rule.id,
          executionId,
          repositoryId: rule.repositoryId,
          triggeredById: context.pullRequestId || context.issueId,
          triggeredByType: context.pullRequestId
            ? "pull_request"
            : context.issueId
              ? "issue"
              : "other",
          triggerEvent: event,
          errorMessage:
            error instanceof Error ? error.message : "Unknown error",
        });
      }
    }

    return { triggered: rules.length, executed };
  } catch (error) {
    logger.error("Failed to trigger automation", {
      repositoryId,
      event,
      error: error instanceof Error ? error.message : "Unknown error",
    });
    throw error;
  }
}

/**
 * Evaluate conditions against the context
 */
async function evaluateConditions(
  conditions: AutomationCondition[],
  context: Record<string, unknown>,
): Promise<boolean> {
  if (conditions.length === 0) return true;

  for (const condition of conditions) {
    const value = getNestedValue(context, condition.field);
    const matched = evaluateCondition(
      condition.operator,
      value,
      condition.value,
    );

    if (!matched) return false;
  }

  return true;
}

function getNestedValue(obj: Record<string, unknown>, path: string): unknown {
  return path
    .split(".")
    .reduce<unknown>(
      (acc, key) =>
        acc && typeof acc === "object"
          ? (acc as Record<string, unknown>)[key]
          : undefined,
      obj as unknown,
    );
}

function evaluateCondition(
  operator: string,
  actual: unknown,
  expected: unknown,
): boolean {
  switch (operator) {
    case "equals":
      return actual === expected;
    case "not_equals":
      return actual !== expected;
    case "contains":
      if (Array.isArray(actual)) {
        return actual.includes(expected);
      }
      if (typeof actual === "string" && typeof expected === "string") {
        return actual.includes(expected);
      }
      return false;
    case "not_contains":
      if (Array.isArray(actual)) {
        return !actual.includes(expected);
      }
      if (typeof actual === "string" && typeof expected === "string") {
        return !actual.includes(expected);
      }
      return true;
    case "matches":
      if (typeof actual === "string" && typeof expected === "string") {
        try {
          // Safety: limit pattern length and apply timeout to prevent ReDoS
          if (expected.length > 200) return false;
          const regex = new RegExp(expected);
          return regex.test(actual.slice(0, 10_000));
        } catch {
          // Invalid regex pattern provided by user
          return false;
        }
      }
      return false;
    case "greater_than":
      return (
        typeof actual === "number" &&
        typeof expected === "number" &&
        actual > expected
      );
    case "less_than":
      return (
        typeof actual === "number" &&
        typeof expected === "number" &&
        actual < expected
      );
    default:
      return false;
  }
}

/**
 * Execute an automation action
 */
async function executeAction(
  action: AutomationAction,
  context: {
    pullRequestId?: string;
    issueId?: string;
    userId?: string;
    metadata?: Record<string, unknown>;
  },
) {
  const db = getDatabase() as NodePgDatabase<typeof schema>;

  switch (action.type) {
    case "add_label": {
      if (context.pullRequestId && action.params.label) {
        // Add label to PR
        await db
          .insert(schema.pullRequestLabels)
          .values({
            id: generateId(),
            pullRequestId: context.pullRequestId,
            labelId: action.params.label as string,
          })
          .onConflictDoNothing();
      }
      break;
    }

    case "remove_label": {
      if (context.pullRequestId && action.params.label) {
        await db
          .delete(schema.pullRequestLabels)
          .where(
            and(
              eq(schema.pullRequestLabels.pullRequestId, context.pullRequestId),
              eq(
                schema.pullRequestLabels.labelId,
                action.params.label as string,
              ),
            ),
          );
      }
      break;
    }

    case "assign_reviewer": {
      if (context.pullRequestId && action.params.assignee) {
        const assignee = action.params.assignee as string;

        // Handle @codeowners - assign reviewers based on CODEOWNERS file
        if (assignee === "@codeowners") {
          try {
            // Get PR details with changed files
            const pr = await db.query.pullRequests.findFirst({
              where: eq(schema.pullRequests.id, context.pullRequestId),
              with: { repository: true },
            });

            if (pr && pr.repository) {
              // Dynamically import to avoid circular deps
              const { resolveRepoPath } = await import("./git-storage");
              const { getFileContent } = await import("./git");
              const { CODEOWNERS_PATHS, getSuggestedReviewers } =
                await import("./codeowners");
              const { compareBranches } = await import("./git");

              const repoPath = await resolveRepoPath(pr.repository.diskPath);

              // Try to find CODEOWNERS file
              let codeOwnersContent: string | null = null;
              for (const path of CODEOWNERS_PATHS) {
                try {
                  const result = await getFileContent(
                    repoPath,
                    path,
                    pr.baseBranch,
                  );
                  if (result && !result.isBinary) {
                    codeOwnersContent = result.content;
                    break;
                  }
                } catch {
                  // File doesn't exist at this path
                }
              }

              if (codeOwnersContent) {
                // Get changed files
                const { diffs } = await compareBranches(
                  repoPath,
                  pr.baseBranch,
                  pr.headBranch,
                );
                const changedFiles = diffs.map((d) => d.file);

                // Get PR author username for exclusion
                const prAuthor = await db.query.users.findFirst({
                  where: eq(schema.users.id, pr.authorId),
                });

                // Get suggested reviewers
                const { owners } = await getSuggestedReviewers(
                  codeOwnersContent,
                  changedFiles,
                  prAuthor ? [prAuthor.username] : [],
                );

                // Add each owner as reviewer
                for (const owner of owners) {
                  const user = await db.query.users.findFirst({
                    where: eq(schema.users.username, owner),
                  });

                  if (user) {
                    await db
                      .insert(schema.pullRequestReviewers)
                      .values({
                        id: generateId(),
                        pullRequestId: context.pullRequestId,
                        userId: user.id,
                        requestedAt: new Date(),
                      })
                      .onConflictDoNothing();
                  }
                }
              }
            }
          } catch (error) {
            logger.warn({ error }, "Failed to assign CODEOWNERS reviewers");
          }
          break;
        }

        // Find user by username
        const user = await db.query.users.findFirst({
          where: eq(schema.users.username, assignee.replace("@", "")),
        });

        if (user) {
          await db
            .insert(schema.pullRequestReviewers)
            .values({
              id: generateId(),
              pullRequestId: context.pullRequestId,
              userId: user.id,
              requestedAt: new Date(),
            })
            .onConflictDoNothing();
        }
      }
      break;
    }

    case "add_comment": {
      if (context.pullRequestId && action.params.body) {
        await db.insert(schema.pullRequestComments).values({
          id: generateId(),
          pullRequestId: context.pullRequestId,
          authorId: context.userId || "system",
          body: action.params.body as string,
          createdAt: new Date(),
          updatedAt: new Date(),
        });
      } else if (context.issueId && action.params.body) {
        await db.insert(schema.issueComments).values({
          id: generateId(),
          issueId: context.issueId,
          authorId: context.userId || "system",
          body: action.params.body as string,
          createdAt: new Date(),
          updatedAt: new Date(),
        });
      }
      break;
    }

    case "update_issue_status": {
      if (context.issueId && action.params.statusId) {
        // If statusId is a special keyword 'closed' or 'open', update the basic state
        if (action.params.statusId === "closed" || action.params.statusId === "open") {
          await db
            .update(schema.issues)
            .set({ 
              state: action.params.statusId,
              statusId: null, // clear custom status if transitioning to basic state
              updatedAt: new Date()
            })
            .where(eq(schema.issues.id, context.issueId));
        } else {
          // Otherwise, it's a custom status ID
          await db
            .update(schema.issues)
            .set({ 
              statusId: action.params.statusId as string,
              state: "open", // assuming custom statuses map to 'open' state generally unless specified
              updatedAt: new Date() 
            })
            .where(eq(schema.issues.id, context.issueId));
        }
      }
      break;
    }

    case "add_to_merge_queue": {
      if (context.pullRequestId) {
        const { addToMergeQueue } = await import("./merge-queue");
        const pr = await db.query.pullRequests.findFirst({
          where: eq(schema.pullRequests.id, context.pullRequestId),
        });

        if (pr) {
          await addToMergeQueue({
            repositoryId: pr.repositoryId,
            pullRequestId: context.pullRequestId,
            addedById: context.userId || "system",
            mergeMethod:
              (action.params.method as "merge" | "squash" | "rebase") ||
              "squash",
          });
        }
      }
      break;
    }

    case "trigger_ai_review": {
      if (context.pullRequestId) {
        const { triggerAIReview } = await import("./ai-review");
        await triggerAIReview(
          context.pullRequestId,
          context.userId || "system",
          {
            provider: "anthropic" as const,
            model: "claude-3-sonnet" as const,
          },
        );
      }
      break;
    }

    case "notify_slack": {
      if (context.pullRequestId && action.params.channel) {
        const { notifyPrEvent } = await import("./slack-notifications");
        const pr = await db.query.pullRequests.findFirst({
          where: eq(schema.pullRequests.id, context.pullRequestId),
          with: { repository: true, author: true },
        });

        if (pr && pr.repository) {
          // Would need org ID detection
          // await notifyPrEvent(...)
        }
      }
      break;
    }

    case "notify_discord": {
      if (context.pullRequestId && action.params.webhookUrl) {
        const { sendDiscordMessage } = await import("./integrations/discord");
        const pr = await db.query.pullRequests.findFirst({
          where: eq(schema.pullRequests.id, context.pullRequestId),
          with: { repository: true, author: true },
        });

        if (pr && pr.repository) {
          await sendDiscordMessage(action.params.webhookUrl as string, {
            content: `**${pr.title}** (#${pr.number}) in ${pr.repository.name}\nState: ${pr.state}`,
            username: "OpenCodeHub",
          });
        }
      }
      break;
    }

    case "notify_teams": {
      if (context.pullRequestId && action.params.webhookUrl) {
        const { sendTeamsMessage } = await import("./integrations/teams");
        const pr = await db.query.pullRequests.findFirst({
          where: eq(schema.pullRequests.id, context.pullRequestId),
          with: { repository: true, author: true },
        });

        if (pr && pr.repository) {
          await sendTeamsMessage(action.params.webhookUrl as string, {
            "@type": "MessageCard",
            "@context": "http://schema.org/extensions",
            themeColor: "0078d4",
            summary: `PR Update: ${pr.title}`,
            sections: [
              {
                text: `**${pr.title}** (#${pr.number}) in ${pr.repository.name}\nStatus: ${pr.state}`,
              },
            ],
          });
        }
      }
      break;
    }

    case "close_pr": {
      if (context.pullRequestId) {
        await db
          .update(schema.pullRequests)
          .set({
            state: "closed",
            closedAt: new Date(),
            updatedAt: new Date(),
          })
          .where(eq(schema.pullRequests.id, context.pullRequestId));
      }
      break;
    }

    case "assign_user": {
      if (action.params.user) {
        const username = action.params.user as string;
        // Find user
        const user = await db.query.users.findFirst({
          where: eq(schema.users.username, username.replace("@", "")),
        });

        if (user) {
          const { generateId } = await import("./utils");
          if (context.pullRequestId) {
            await db
              .insert(schema.pullRequestAssignees)
              .values({
                id: generateId(),
                pullRequestId: context.pullRequestId,
                userId: user.id,
              })
              .onConflictDoNothing();
          } else if (context.issueId) {
            await db
              .update(schema.issues)
              .set({
                assigneeId: user.id,
                updatedAt: new Date(),
              })
              .where(eq(schema.issues.id, context.issueId));
          }
        }
      }
      break;
    }

    case "request_changes": {
      if (context.pullRequestId && action.params.body) {
        const { generateId } = await import("./utils");
        // Create a review
        await db.insert(schema.pullRequestReviews).values({
          id: generateId(),
          pullRequestId: context.pullRequestId,
          reviewerId: context.userId || "system", // Or a bot user info if available
          state: "changes_requested",
          body: action.params.body as string,
          submittedAt: new Date(),
        });
      }
      break;
    }

    case "trigger_iac_hook": {
      if (context.pullRequestId) {
        const pr = await db.query.pullRequests.findFirst({
          where: eq(schema.pullRequests.id, context.pullRequestId),
        });
        if (pr) {
          const actionType =
            (action.params.action as "plan" | "apply") || "plan";
          const { triggerIaCHooks } = await import("./iac-hooks");
          await triggerIaCHooks({
            repositoryId: pr.repositoryId,
            action: actionType,
            runId:
              typeof action.params.runId === "string"
                ? action.params.runId
                : undefined,
            message:
              typeof action.params.message === "string"
                ? action.params.message
                : undefined,
            configId:
              typeof action.params.configId === "string"
                ? action.params.configId
                : undefined,
          });
        }
      }
      break;
    }

    case "trigger_cloud_deploy": {
      if (context.pullRequestId) {
        const pr = await db.query.pullRequests.findFirst({
          where: eq(schema.pullRequests.id, context.pullRequestId),
        });
        if (pr) {
          const { triggerCloudDeploy } = await import("./cloud-hooks");
          await triggerCloudDeploy({
            repositoryId: pr.repositoryId,
            configId:
              typeof action.params.configId === "string"
                ? action.params.configId
                : undefined,
            imageTag:
              typeof action.params.imageTag === "string"
                ? action.params.imageTag
                : undefined,
            namespace:
              typeof action.params.namespace === "string"
                ? action.params.namespace
                : undefined,
            deploymentName:
              typeof action.params.deploymentName === "string"
                ? action.params.deploymentName
                : undefined,
            serviceName:
              typeof action.params.serviceName === "string"
                ? action.params.serviceName
                : undefined,
            appName:
              typeof action.params.appName === "string"
                ? action.params.appName
                : undefined,
            taskDefinition:
              typeof action.params.taskDefinition === "string"
                ? action.params.taskDefinition
                : undefined,
            clusterName:
              typeof action.params.clusterName === "string"
                ? action.params.clusterName
                : undefined,
          });
        }
      }
      break;
    }

    default:
      logger.warn("Unknown automation action", { type: action.type });
  }
}

/**
 * Create an automation rule
 */
export async function createAutomationRule(options: {
  repositoryId?: string;
  organizationId?: string;
  createdById: string;
  name: string;
  description?: string;
  trigger: AutomationTrigger;
  conditions?: AutomationCondition[];
  actions: AutomationAction[];
  priority?: number;
}) {
  const db = getDatabase() as NodePgDatabase<typeof schema>;

  const rule = {
    id: generateId(),
    repositoryId: options.repositoryId,
    organizationId: options.organizationId,
    createdById: options.createdById,
    name: options.name,
    description: options.description,
    trigger: options.trigger,
    conditions: options.conditions ? JSON.stringify(options.conditions) : null,
    actions: JSON.stringify(options.actions),
    isEnabled: true,
    priority: options.priority || 0,
    createdAt: new Date(),
    updatedAt: new Date(),
  };

  await db.insert(schema.automationRules).values(rule);

  return rule;
}

/**
 * Get automation rules for a repository
 */
export async function getAutomationRules(repositoryId: string) {
  const db = getDatabase() as NodePgDatabase<typeof schema>;

  return db.query.automationRules.findMany({
    where: eq(schema.automationRules.repositoryId, repositoryId),
    orderBy: [
      desc(schema.automationRules.priority),
      desc(schema.automationRules.createdAt),
    ],
  });
}

/**
 * Toggle automation rule enabled state
 */
export async function toggleAutomationRule(ruleId: string, enabled: boolean) {
  const db = getDatabase() as NodePgDatabase<typeof schema>;

  await db
    .update(schema.automationRules)
    .set({
      isEnabled: enabled,
      updatedAt: new Date(),
    })
    .where(eq(schema.automationRules.id, ruleId));
}

/**
 * Delete an automation rule
 */
export async function deleteAutomationRule(ruleId: string) {
  const db = getDatabase() as NodePgDatabase<typeof schema>;

  await db
    .delete(schema.automationRules)
    .where(eq(schema.automationRules.id, ruleId));
}