bookwiz.io / app / api / profile / tour-tracking / route.ts
route.ts
Raw
import { NextRequest, NextResponse } from 'next/server'
import { createClient } from '@supabase/supabase-js'

const supabase = createClient(
  process.env.NEXT_PUBLIC_SUPABASE_URL!,
  process.env.SUPABASE_SERVICE_ROLE_KEY!
)

export async function POST(request: NextRequest) {
  try {
    // Get the authorization header
    const authHeader = request.headers.get('authorization')
    if (!authHeader) {
      return NextResponse.json({ error: 'No authorization header' }, { status: 401 })
    }

    // Create a Supabase client with the user's session
    const userSupabase = createClient(
      process.env.NEXT_PUBLIC_SUPABASE_URL!,
      process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
      {
        global: {
          headers: {
            Authorization: authHeader
          }
        }
      }
    )

    // Get the current user
    const { data: { user }, error: userError } = await userSupabase.auth.getUser()
    
    if (userError || !user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const body = await request.json()
    const { action, ...trackingData } = body

    let updateData: any = {
      updated_at: new Date().toISOString()
    }

    switch (action) {
      case 'start':
        const { tourVersion: startVersion } = trackingData
        updateData = {
          ...updateData,
          welcome_tour_started_at: new Date().toISOString(),
          welcome_tour_current_step: 0,
          welcome_tour_steps_viewed: [0],
          welcome_tour_version: startVersion || 'v1'
        }
        break

      case 'step':
        const { stepIndex, stepsViewed, tourVersion: stepVersion } = trackingData
        updateData = {
          ...updateData,
          welcome_tour_current_step: stepIndex,
          welcome_tour_steps_viewed: stepsViewed,
          welcome_tour_version: stepVersion || 'v1'
        }
        break

      case 'video_watched':
        const { tourVersion: videoVersion } = trackingData
        updateData = {
          ...updateData,
          welcome_tour_video_watched: true,
          welcome_tour_version: videoVersion || 'v1'
        }
        break

      case 'plan_selected':
        const { plan, billing, tourVersion: planVersion } = trackingData
        updateData = {
          ...updateData,
          welcome_tour_selected_plan: plan,
          welcome_tour_selected_billing: billing,
          welcome_tour_version: planVersion || 'v1'
        }
        break

      case 'complete':
        const { plan: selectedPlan, billing: selectedBilling, totalTimeSeconds, tourVersion: completeVersion } = trackingData
        updateData = {
          ...updateData,
          welcome_tour_completed: true,
          welcome_tour_completed_at: new Date().toISOString(),
          welcome_tour_completion_type: 'completed',
          welcome_tour_selected_plan: selectedPlan,
          welcome_tour_selected_billing: selectedBilling,
          welcome_tour_total_time_seconds: totalTimeSeconds,
          welcome_tour_version: completeVersion || 'v1'
        }
        break

      case 'close':
        const { completionType, totalTimeSeconds: closeTime, tourVersion: closeVersion } = trackingData
        updateData = {
          ...updateData,
          welcome_tour_completed: true,
          welcome_tour_completed_at: new Date().toISOString(),
          welcome_tour_completion_type: completionType,
          welcome_tour_total_time_seconds: closeTime,
          welcome_tour_version: closeVersion || 'v1'
        }
        break

      default:
        return NextResponse.json({ error: 'Invalid action' }, { status: 400 })
    }

    // Update the user's profile
    const { error: updateError } = await supabase
      .from('profiles')
      .update(updateData)
      .eq('id', user.id)

    if (updateError) {
      console.error('Error updating profile:', updateError)
      return NextResponse.json({ error: 'Failed to update profile' }, { status: 500 })
    }

    return NextResponse.json({ success: true })

  } catch (error) {
    console.error('Error in tour-tracking API:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}