bookwiz.io / app / api / profile / email-preferences / route.ts
route.ts
Raw
import { NextRequest, NextResponse } from 'next/server'
import { createClient } from '@supabase/supabase-js'
import type { Database } from '@/lib/supabase-types'

// Create server-side Supabase client with user session
function createServerSupabaseClient(request: Request) {
  // Get the authorization header from the request
  const authHeader = request.headers.get('authorization')
  
  return createClient<Database>(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      auth: {
        autoRefreshToken: false,
        persistSession: false
      },
      global: {
        headers: authHeader ? {
          Authorization: authHeader
        } : {}
      }
    }
  )
}

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const userId = searchParams.get('userId')

    if (!userId) {
      return NextResponse.json({ error: 'User ID is required' }, { status: 400 })
    }

    const supabase = createServerSupabaseClient(request)

    // Verify user is authenticated and can only view their own preferences
    const { data: { user }, error: authError } = await supabase.auth.getUser()
    if (authError || !user || user.id !== userId) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    // Get user's email preferences
    const { data, error } = await supabase
      .from('email_preferences')
      .select('*')
      .eq('user_id', userId)
      .single()

    if (error) {
      // If no preferences found, return defaults
      if (error.code === 'PGRST116') {
        return NextResponse.json({
          preferences: {
            weekly_progress_digest: true,
            product_updates: true,
            account_notifications: true
          }
        })
      }
      throw error
    }

    return NextResponse.json({
      preferences: {
        weekly_progress_digest: data.weekly_progress_digest,
        product_updates: data.product_updates,
        account_notifications: data.account_notifications
      }
    })

  } catch (error) {
    console.error('Error fetching email preferences:', error)
    return NextResponse.json(
      { error: 'Failed to fetch email preferences' },
      { status: 500 }
    )
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { userId, weekly_progress_digest, product_updates, account_notifications } = body

    if (!userId) {
      return NextResponse.json({ error: 'User ID is required' }, { status: 400 })
    }

    const supabase = createServerSupabaseClient(request)

    // Verify user is authenticated and can only update their own preferences
    const { data: { user }, error: authError } = await supabase.auth.getUser()
    if (authError || !user || user.id !== userId) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    // Update or insert email preferences
    const { data, error } = await supabase
      .from('email_preferences')
      .upsert({
        user_id: userId,
        weekly_progress_digest: weekly_progress_digest ?? true,
        product_updates: product_updates ?? true,
        account_notifications: account_notifications ?? true,
        updated_at: new Date().toISOString()
      })
      .select()
      .single()

    if (error) {
      throw error
    }

    return NextResponse.json({
      message: 'Email preferences updated successfully',
      preferences: {
        weekly_progress_digest: data.weekly_progress_digest,
        product_updates: data.product_updates,
        account_notifications: data.account_notifications
      }
    })

  } catch (error) {
    console.error('Error updating email preferences:', error)
    return NextResponse.json(
      { error: 'Failed to update email preferences' },
      { status: 500 }
    )
  }
}