/**
 * Webhook Configuration tRPC Router
 * Handles webhook configuration, testing, and management
 */

import { router, protectedProcedure, adminProcedure } from '../_core/trpc.ts';
import { webhookConfigService } from '../services/webhookConfigService.ts';
import { z } from 'zod';

export const webhookConfigRouter = router({
  /**
   * Get current webhook configuration (admin only)
   */
  getConfig: adminProcedure.query(async () => {
    return webhookConfigService.getConfig();
  }),

  /**
   * Set Slack webhook URL (admin only)
   */
  setSlackWebhook: adminProcedure
    .input(
      z.object({
        webhookUrl: z.string().url(),
        enabled: z.boolean().optional().default(true),
      })
    )
    .mutation(async ({ input }) => {
      try {
        webhookConfigService.setSlackWebhook(input.webhookUrl, input.enabled);
        return { success: true, message: 'Slack webhook configured successfully' };
      } catch (error) {
        return {
          success: false,
          message: error instanceof Error ? error.message : 'Failed to configure Slack webhook',
        };
      }
    }),

  /**
   * Set PagerDuty integration key (admin only)
   */
  setPagerDutyKey: adminProcedure
    .input(
      z.object({
        integrationKey: z.string(),
        enabled: z.boolean().optional().default(true),
      })
    )
    .mutation(async ({ input }) => {
      try {
        webhookConfigService.setPagerDutyKey(input.integrationKey, input.enabled);
        return { success: true, message: 'PagerDuty integration configured successfully' };
      } catch (error) {
        return {
          success: false,
          message: error instanceof Error ? error.message : 'Failed to configure PagerDuty',
        };
      }
    }),

  /**
   * Set email recipients (admin only)
   */
  setEmailRecipients: adminProcedure
    .input(
      z.object({
        recipients: z.array(z.string().email()),
        enabled: z.boolean().optional().default(true),
      })
    )
    .mutation(async ({ input }) => {
      try {
        webhookConfigService.setEmailRecipients(input.recipients, input.enabled);
        return { success: true, message: 'Email recipients configured successfully' };
      } catch (error) {
        return {
          success: false,
          message: error instanceof Error ? error.message : 'Failed to configure email recipients',
        };
      }
    }),

  /**
   * Enable/disable Slack webhook (admin only)
   */
  setSlackEnabled: adminProcedure
    .input(z.object({ enabled: z.boolean() }))
    .mutation(async ({ input }) => {
      webhookConfigService.setSlackEnabled(input.enabled);
      return {
        success: true,
        message: `Slack webhook ${input.enabled ? 'enabled' : 'disabled'}`,
      };
    }),

  /**
   * Enable/disable PagerDuty webhook (admin only)
   */
  setPagerDutyEnabled: adminProcedure
    .input(z.object({ enabled: z.boolean() }))
    .mutation(async ({ input }) => {
      webhookConfigService.setPagerDutyEnabled(input.enabled);
      return {
        success: true,
        message: `PagerDuty webhook ${input.enabled ? 'enabled' : 'disabled'}`,
      };
    }),

  /**
   * Enable/disable email webhook (admin only)
   */
  setEmailEnabled: adminProcedure
    .input(z.object({ enabled: z.boolean() }))
    .mutation(async ({ input }) => {
      webhookConfigService.setEmailEnabled(input.enabled);
      return {
        success: true,
        message: `Email webhook ${input.enabled ? 'enabled' : 'disabled'}`,
      };
    }),

  /**
   * Test Slack webhook (admin only)
   */
  testSlackWebhook: adminProcedure.mutation(async () => {
    const result = await webhookConfigService.testSlackWebhook();
    return result;
  }),

  /**
   * Test PagerDuty webhook (admin only)
   */
  testPagerDutyWebhook: adminProcedure.mutation(async () => {
    const result = await webhookConfigService.testPagerDutyWebhook();
    return result;
  }),

  /**
   * Test email webhook (admin only)
   */
  testEmailWebhook: adminProcedure.mutation(async () => {
    const result = await webhookConfigService.testEmailWebhook();
    return result;
  }),

  /**
   * Test all webhooks (admin only)
   */
  testAllWebhooks: adminProcedure.mutation(async () => {
    const results = await webhookConfigService.testAllWebhooks();
    return {
      results,
      summary: {
        total: results.length,
        successful: results.filter((r) => r.success).length,
        failed: results.filter((r) => !r.success).length,
      },
    };
  }),

  /**
   * Get test results (admin only)
   */
  getTestResults: adminProcedure
    .input(z.object({ limit: z.number().optional().default(50) }))
    .query(async ({ input }) => {
      return webhookConfigService.getTestResults(input.limit);
    }),

  /**
   * Get test results by channel (admin only)
   */
  getTestResultsByChannel: adminProcedure
    .input(
      z.object({
        channel: z.enum(['slack', 'pagerduty', 'email']),
        limit: z.number().optional().default(20),
      })
    )
    .query(async ({ input }) => {
      return webhookConfigService.getTestResultsByChannel(input.channel, input.limit);
    }),

  /**
   * Get latest test results for each channel (admin only)
   */
  getLatestTestResults: adminProcedure.query(async () => {
    return webhookConfigService.getLatestTestResults();
  }),

  /**
   * Validate webhook configuration (admin only)
   */
  validateConfig: adminProcedure.query(async () => {
    return webhookConfigService.validate();
  }),

  /**
   * Clear test results (admin only)
   */
  clearTestResults: adminProcedure.mutation(async () => {
    webhookConfigService.clearTestResults();
    return { success: true, message: 'Test results cleared' };
  }),
});
