import { router, protectedProcedure } from '../_core/trpc.ts';
import { z } from 'zod';
import { adminNotificationService } from '../_core/adminNotifications.ts';
import { TRPCError } from '@trpc/server';

export const adminAlertsRouter = router({
  /**
   * Get all alerts for current admin
   */
  getAlerts: protectedProcedure
    .input(
      z.object({
        unreadOnly: z.boolean().optional().default(false),
      })
    )
    .query(({ ctx, input }) => {
      if (ctx.user.role !== 'admin') {
        throw new TRPCError({ code: 'FORBIDDEN' });
      }

      return adminNotificationService.getAdminAlerts(ctx.user.id, input.unreadOnly);
    }),

  /**
   * Get alert statistics
   */
  getStats: protectedProcedure.query(({ ctx }) => {
    if (ctx.user.role !== 'admin') {
      throw new TRPCError({ code: 'FORBIDDEN' });
    }

    return adminNotificationService.getAlertStats(ctx.user.id);
  }),

  /**
   * Mark alert as read
   */
  markAsRead: protectedProcedure
    .input(z.object({ alertId: z.string() }))
    .mutation(({ ctx, input }) => {
      if (ctx.user.role !== 'admin') {
        throw new TRPCError({ code: 'FORBIDDEN' });
      }

      adminNotificationService.markAlertAsRead(input.alertId);
      return { success: true };
    }),

  /**
   * Mark all alerts as read
   */
  markAllAsRead: protectedProcedure.mutation(({ ctx }) => {
    if (ctx.user.role !== 'admin') {
      throw new TRPCError({ code: 'FORBIDDEN' });
    }

    adminNotificationService.markAllAlertsAsRead(ctx.user.id);
    return { success: true };
  }),

  /**
   * Delete alert
   */
  deleteAlert: protectedProcedure
    .input(z.object({ alertId: z.string() }))
    .mutation(({ ctx, input }) => {
      if (ctx.user.role !== 'admin') {
        throw new TRPCError({ code: 'FORBIDDEN' });
      }

      adminNotificationService.deleteAlert(input.alertId);
      return { success: true };
    }),

  /**
   * Get notification preferences
   */
  getPreferences: protectedProcedure.query(({ ctx }) => {
    if (ctx.user.role !== 'admin') {
      throw new TRPCError({ code: 'FORBIDDEN' });
    }

    return adminNotificationService.getPreferences(ctx.user.id);
  }),

  /**
   * Update notification preferences
   */
  updatePreferences: protectedProcedure
    .input(
      z.object({
        emailOnCritical: z.boolean().optional(),
        emailOnHigh: z.boolean().optional(),
        emailOnMedium: z.boolean().optional(),
        emailOnLow: z.boolean().optional(),
        smsOnCritical: z.boolean().optional(),
        inAppNotifications: z.boolean().optional(),
        digestFrequency: z.enum(['immediate', 'hourly', 'daily', 'weekly']).optional(),
      })
    )
    .mutation(({ ctx, input }) => {
      if (ctx.user.role !== 'admin') {
        throw new TRPCError({ code: 'FORBIDDEN' });
      }

      adminNotificationService.setPreferences(ctx.user.id, input);
      return { success: true };
    }),

  /**
   * Create a test alert (for testing purposes)
   */
  createTestAlert: protectedProcedure.mutation(async ({ ctx }) => {
    if (ctx.user.role !== 'admin') {
      throw new TRPCError({ code: 'FORBIDDEN' });
    }

    const alert = await adminNotificationService.createAlert(
      'system_error',
      'high',
      'Test Alert',
      'This is a test alert to verify the notification system is working correctly.',
      ctx.user.id,
      '/admin/dashboard'
    );

    return alert;
  }),
});
