All files / src/app/api/user/email-preferences route.ts

0% Statements 0/134
100% Branches 0/0
0% Functions 0/1
0% Lines 0/134

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135                                                                                                                                                                                                                                                                             
/**
 * Email Preferences API
 *
 * Allows authenticated users to manage their email notification preferences.
 */

import { NextRequest, NextResponse } from 'next/server';
import {
  withAuth,
  withErrorHandling,
  successResponse,
  ApiError,
  ApiSuccessResponse,
  ApiErrorResponse
} from '@/lib/api';
import { RouteContext } from '@/lib/api/middleware';
import { prisma } from '@/lib/prisma';
import { z } from 'zod';
import { Session } from 'next-auth';
import crypto from 'crypto';

// Validation schema for updating preferences
const UpdatePreferencesSchema = z.object({
  orderUpdates: z.boolean().optional(),
  promotions: z.boolean().optional(),
  newsletters: z.boolean().optional(),
  productAlerts: z.boolean().optional(),
  unsubscribeAll: z.boolean().optional()
});

// Response type
interface EmailPreferencesResponse {
  id: number;
  orderUpdates: boolean;
  promotions: boolean;
  newsletters: boolean;
  productAlerts: boolean;
  unsubscribeAll: boolean;
  updatedAt: Date;
}

/**
 * GET /api/user/email-preferences
 *
 * Get user's email notification preferences
 */
async function handleGet(
  _request: NextRequest,
  _context: RouteContext | undefined,
  session: Session
): Promise<NextResponse<ApiSuccessResponse<EmailPreferencesResponse> | ApiErrorResponse>> {
  const userId = session.user.id;

  // Get or create preferences
  let preferences = await prisma.emailPreference.findUnique({
    where: { userId }
  });

  // If no preferences exist, create default ones
  if (!preferences) {
    preferences = await prisma.emailPreference.create({
      data: {
        userId,
        unsubscribeToken: crypto.randomBytes(32).toString('hex')
      }
    });
  }

  return successResponse({
    id: preferences.id,
    orderUpdates: preferences.orderUpdates,
    promotions: preferences.promotions,
    newsletters: preferences.newsletters,
    productAlerts: preferences.productAlerts,
    unsubscribeAll: preferences.unsubscribeAll,
    updatedAt: preferences.updatedAt
  });
}

/**
 * PATCH /api/user/email-preferences
 *
 * Update user's email notification preferences
 */
async function handlePatch(
  request: NextRequest,
  _context: RouteContext | undefined,
  session: Session
): Promise<NextResponse<ApiSuccessResponse<EmailPreferencesResponse> | ApiErrorResponse>> {
  const userId = session.user.id;
  const body = await request.json();

  // Validate input
  const validation = UpdatePreferencesSchema.safeParse(body);
  if (!validation.success) {
    throw ApiError.validation(
      'Validation failed',
      validation.error.flatten().fieldErrors
    );
  }

  const updates = validation.data;

  // If unsubscribing from all, set all marketing preferences to false
  if (updates.unsubscribeAll === true) {
    updates.promotions = false;
    updates.newsletters = false;
    updates.productAlerts = false;
  }

  // Upsert preferences
  const preferences = await prisma.emailPreference.upsert({
    where: { userId },
    create: {
      userId,
      ...updates,
      unsubscribeToken: crypto.randomBytes(32).toString('hex')
    },
    update: updates
  });

  return successResponse({
    id: preferences.id,
    orderUpdates: preferences.orderUpdates,
    promotions: preferences.promotions,
    newsletters: preferences.newsletters,
    productAlerts: preferences.productAlerts,
    unsubscribeAll: preferences.unsubscribeAll,
    updatedAt: preferences.updatedAt
  });
}

export const GET = withErrorHandling(withAuth(handleGet));
export const PATCH = withErrorHandling(withAuth(handlePatch));