import { router, protectedProcedure, adminProcedure } from "../_core/trpc.ts";
import { z } from 'zod';
import { TRPCError } from '@trpc/server';
import { logActivity } from "../_core/activityLogger.ts";

export const adminInviteTrackingRouter = router({
  /**
   * Record invite acceptance
   */
  recordAcceptance: protectedProcedure
    .input(
      z.object({
        inviteToken: z.string(),
        adminId: z.string(),
        acceptedAt: z.date().optional(),
      })
    )
    .mutation(async ({ input, ctx }) => {
      try {
        const acceptedAt = input.acceptedAt || new Date();

        // Log activity
        await logActivity({
          adminId: ctx.user.id,
          action: 'INVITE_ACCEPTED',
          resourceType: 'admin_invite',
          resourceId: input.inviteToken,
          details: {
            newAdminId: input.adminId,
            acceptedAt: acceptedAt.toISOString(),
          },
        });

        return {
          success: true,
          acceptedAt: acceptedAt.toISOString(),
        };
      } catch (error) {
        console.error('[InviteTracking] Error recording acceptance:', error);
        throw new TRPCError({
          code: 'INTERNAL_SERVER_ERROR',
          message: 'Failed to record invite acceptance',
        });
      }
    }),

  /**
   * Get invite acceptance statistics
   */
  getAcceptanceStats: adminProcedure.query(async ({ ctx }) => {
    try {
      // This would query acceptance data from database
      // For now returning placeholder stats
      return {
        totalInvites: 0,
        acceptedInvites: 0,
        pendingInvites: 0,
        expiredInvites: 0,
        acceptanceRate: 0,
        averageTimeToAccept: 0, // in hours
      };
    } catch (error) {
      console.error('[InviteTracking] Error fetching stats:', error);
      throw new TRPCError({
        code: 'INTERNAL_SERVER_ERROR',
        message: 'Failed to fetch acceptance statistics',
      });
    }
  }),

  /**
   * Get acceptance history for admin
   */
  getAcceptanceHistory: adminProcedure
    .input(
      z.object({
        limit: z.number().default(20),
        offset: z.number().default(0),
      })
    )
    .query(async ({ input }) => {
      try {
        // This would query acceptance history from database
        return {
          history: [],
          total: 0,
          hasMore: false,
        };
      } catch (error) {
        console.error('[InviteTracking] Error fetching history:', error);
        throw new TRPCError({
          code: 'INTERNAL_SERVER_ERROR',
          message: 'Failed to fetch acceptance history',
        });
      }
    }),

  /**
   * Send acceptance confirmation email
   */
  sendAcceptanceConfirmation: adminProcedure
    .input(
      z.object({
        invitedByAdminEmail: z.string().email(),
        newAdminName: z.string(),
        newAdminEmail: z.string().email(),
      })
    )
    .mutation(async ({ input, ctx }) => {
      try {
        // Log activity
        await logActivity({
          adminId: ctx.user.id,
          action: 'ACCEPTANCE_CONFIRMATION_SENT',
          resourceType: 'admin_invite',
          resourceId: input.newAdminEmail,
          details: {
            invitedByEmail: input.invitedByAdminEmail,
            newAdminName: input.newAdminName,
            newAdminEmail: input.newAdminEmail,
          },
        });

        return { success: true };
      } catch (error) {
        console.error('[InviteTracking] Error sending confirmation:', error);
        throw new TRPCError({
          code: 'INTERNAL_SERVER_ERROR',
          message: 'Failed to send acceptance confirmation',
        });
      }
    }),

  /**
   * Get detailed invite metrics
   */
  getDetailedMetrics: adminProcedure.query(async ({ ctx }) => {
    try {
      return {
        byRole: {
          admin: { total: 0, accepted: 0, pending: 0, expired: 0 },
          moderator: { total: 0, accepted: 0, pending: 0, expired: 0 },
          finance_team: { total: 0, accepted: 0, pending: 0, expired: 0 },
          developer: { total: 0, accepted: 0, pending: 0, expired: 0 },
          support_lead: { total: 0, accepted: 0, pending: 0, expired: 0 },
        },
        byMonth: [],
        acceptanceTimeDistribution: {
          withinDay: 0,
          withinWeek: 0,
          withinMonth: 0,
          overMonth: 0,
        },
      };
    } catch (error) {
      console.error('[InviteTracking] Error fetching metrics:', error);
      throw new TRPCError({
        code: 'INTERNAL_SERVER_ERROR',
        message: 'Failed to fetch detailed metrics',
      });
    }
  }),
});
