import { router, protectedProcedure } from '../_core/trpc.js.ts';
import { z } from 'zod';
import PushNotificationCampaignsService from '../pushNotificationCampaignsService.js';

const campaignsService = new PushNotificationCampaignsService();

export const pushNotificationCampaignsRouter = router({
  /**
   * Create a new campaign
   */
  createCampaign: protectedProcedure
    .input(
      z.object({
        title: z.string().min(1).max(200),
        message: z.string().min(1).max(1000),
        segment: z.enum(['all', 'new_players', 'vip', 'inactive', 'high_spenders', 'tournament_players']),
        imageUrl: z.string().optional(),
        ctaText: z.string().optional(),
        ctaUrl: z.string().optional(),
        scheduledFor: z.date().optional(),
      })
    )
    .mutation(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return campaignsService.createCampaign(
        input.title,
        input.message,
        input.segment,
        ctx.user.id,
        {
          imageUrl: input.imageUrl,
          ctaText: input.ctaText,
          ctaUrl: input.ctaUrl,
          scheduledFor: input.scheduledFor,
        }
      );
    }),

  /**
   * Send campaign
   */
  sendCampaign: protectedProcedure
    .input(z.object({ campaignId: z.string() }))
    .mutation(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return campaignsService.sendCampaign(input.campaignId);
    }),

  /**
   * Schedule campaign
   */
  scheduleCampaign: protectedProcedure
    .input(z.object({ campaignId: z.string(), scheduledFor: z.date() }))
    .mutation(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return campaignsService.scheduleCampaign(input.campaignId, input.scheduledFor);
    }),

  /**
   * Pause campaign
   */
  pauseCampaign: protectedProcedure
    .input(z.object({ campaignId: z.string() }))
    .mutation(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return campaignsService.pauseCampaign(input.campaignId);
    }),

  /**
   * Resume campaign
   */
  resumeCampaign: protectedProcedure
    .input(z.object({ campaignId: z.string() }))
    .mutation(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return campaignsService.resumeCampaign(input.campaignId);
    }),

  /**
   * Cancel campaign
   */
  cancelCampaign: protectedProcedure
    .input(z.object({ campaignId: z.string() }))
    .mutation(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return campaignsService.cancelCampaign(input.campaignId);
    }),

  /**
   * Update campaign
   */
  updateCampaign: protectedProcedure
    .input(
      z.object({
        campaignId: z.string(),
        title: z.string().optional(),
        message: z.string().optional(),
        imageUrl: z.string().optional(),
        ctaText: z.string().optional(),
        ctaUrl: z.string().optional(),
      })
    )
    .mutation(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      const { campaignId, ...updates } = input;
      return campaignsService.updateCampaign(campaignId, updates);
    }),

  /**
   * Get campaign
   */
  getCampaign: protectedProcedure
    .input(z.object({ campaignId: z.string() }))
    .query(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return campaignsService.getCampaign(input.campaignId);
    }),

  /**
   * Get all campaigns
   */
  getAllCampaigns: protectedProcedure.query(({ ctx }) => {
    // Check if user is admin
    if (ctx.user.role !== 'admin') {
      throw new Error('Unauthorized');
    }

    return campaignsService.getAllCampaigns();
  }),

  /**
   * Get campaigns by status
   */
  getCampaignsByStatus: protectedProcedure
    .input(z.object({ status: z.enum(['draft', 'scheduled', 'sent', 'paused', 'cancelled']) }))
    .query(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return campaignsService.getCampaignsByStatus(input.status);
    }),

  /**
   * Get templates
   */
  getTemplates: protectedProcedure.query(({ ctx }) => {
    // Check if user is admin
    if (ctx.user.role !== 'admin') {
      throw new Error('Unauthorized');
    }

    return campaignsService.getTemplates();
  }),

  /**
   * Create template
   */
  createTemplate: protectedProcedure
    .input(
      z.object({
        name: z.string().min(1).max(100),
        title: z.string().min(1).max(200),
        message: z.string().min(1).max(1000),
        category: z.enum(['promotion', 'announcement', 'event', 'reward', 'engagement']),
        imageUrl: z.string().optional(),
        ctaText: z.string().optional(),
        ctaUrl: z.string().optional(),
      })
    )
    .mutation(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return campaignsService.createTemplate(
        input.name,
        input.title,
        input.message,
        input.category,
        {
          imageUrl: input.imageUrl,
          ctaText: input.ctaText,
          ctaUrl: input.ctaUrl,
        }
      );
    }),

  /**
   * Get segment user count
   */
  getSegmentUserCount: protectedProcedure
    .input(z.object({ segment: z.enum(['all', 'new_players', 'vip', 'inactive', 'high_spenders', 'tournament_players']) }))
    .query(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return campaignsService.getSegmentUserCount(input.segment);
    }),

  /**
   * Get campaign statistics
   */
  getCampaignStatistics: protectedProcedure
    .input(z.object({ campaignId: z.string() }))
    .query(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return campaignsService.getCampaignStatistics(input.campaignId);
    }),

  /**
   * Get all campaigns statistics
   */
  getAllCampaignsStatistics: protectedProcedure.query(({ ctx }) => {
    // Check if user is admin
    if (ctx.user.role !== 'admin') {
      throw new Error('Unauthorized');
    }

    return campaignsService.getAllCampaignsStatistics();
  }),
});

export default pushNotificationCampaignsRouter;
