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

const abTestingService = new ABTestingService();

export const abTestingRouter = router({
  /**
   * Create A/B test
   */
  createTest: protectedProcedure
    .input(
      z.object({
        campaignId: z.string(),
        name: z.string().min(1).max(200),
        description: z.string().optional(),
        variants: z.array(
          z.object({
            variantName: z.string().min(1),
            title: z.string().min(1),
            message: z.string().min(1),
            imageUrl: z.string().optional(),
            ctaText: z.string().optional(),
            ctaUrl: z.string().optional(),
            splitPercentage: z.number().min(0).max(100),
          })
        ),
      })
    )
    .mutation(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return abTestingService.createTest(
        input.campaignId,
        input.name,
        input.variants,
        input.description
      );
    }),

  /**
   * Start A/B test
   */
  startTest: protectedProcedure
    .input(z.object({ testId: z.string(), startDate: z.date().optional() }))
    .mutation(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return abTestingService.startTest(input.testId, input.startDate);
    }),

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

      return abTestingService.pauseTest(input.testId);
    }),

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

      return abTestingService.resumeTest(input.testId);
    }),

  /**
   * Complete A/B test
   */
  completeTest: protectedProcedure
    .input(z.object({ testId: z.string(), winnerVariantId: z.string() }))
    .mutation(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      return abTestingService.completeTest(input.testId, input.winnerVariantId);
    }),

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

      return abTestingService.cancelTest(input.testId);
    }),

  /**
   * Track variant event
   */
  trackVariantEvent: protectedProcedure
    .input(
      z.object({
        variantId: z.string(),
        eventType: z.enum(['sent', 'delivered', 'opened', 'clicked']),
      })
    )
    .mutation(({ input, ctx }) => {
      // Check if user is admin
      if (ctx.user.role !== 'admin') {
        throw new Error('Unauthorized');
      }

      const success = abTestingService.trackVariantEvent(input.variantId, input.eventType);
      return { success };
    }),

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

      return abTestingService.getTest(input.testId);
    }),

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

    return abTestingService.getAllTests();
  }),

  /**
   * Get tests by campaign
   */
  getTestsByCampaign: 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 abTestingService.getTestsByCampaign(input.campaignId);
    }),

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

      return abTestingService.getTestResults(input.testId);
    }),

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

      return abTestingService.getWinnerRecommendation(input.testId);
    }),

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

      return abTestingService.getStatisticalSignificance(input.testId);
    }),

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

    return abTestingService.getAllTestsStatistics();
  }),
});

export default abTestingRouter;
