← back to Dear Bubbe Nextjs

app/api/local-content/route.ts

156 lines

/**
 * Local Content API for Super Max Tier
 * 
 * Provides hyper-local news, sports, and weather
 * with Bubbe's personalized commentary
 */

import { NextRequest, NextResponse } from 'next/server';
import {
  getLocalNews,
  getLocalSports,
  getLocalWeather,
  getUserLocation,
  getPersonalizedLocalResponse,
  hasSuperMaxAccess
} from '@/lib/local-content-handler';
import { getUserSession } from '@/lib/user-session';

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const { type, message, userId: providedUserId } = body;
    
    // Get or generate user ID
    const userId = providedUserId || 
                   req.cookies.get('userId')?.value ||
                   req.headers.get('x-user-id') ||
                   `user_${Date.now()}`;
    
    // Check if user has Super Max plan
    const session = getUserSession(userId);
    if (session.plan !== 'supermax') {
      return NextResponse.json({
        error: 'feature_locked',
        message: `Local content? Oh, NOW you want to know everything about your neighborhood? Fork over $54 for Super Max and I'll be your personal yenta!`,
        requiredPlan: 'supermax',
        currentPlan: session.plan
      }, { status: 402 });
    }
    
    // Get user's location
    const location = await getUserLocation(req);
    const city = location.city || 'your city';
    
    let result;
    
    switch (type) {
      case 'news':
        result = await getLocalNews(userId, city);
        break;
        
      case 'sports':
        result = await getLocalSports(userId, city);
        break;
        
      case 'weather':
        if (!location.latitude || !location.longitude) {
          return NextResponse.json({
            error: 'location_required',
            message: `I can't tell you the weather if I don't know where you are! What am I, a mind reader?`
          }, { status: 400 });
        }
        result = await getLocalWeather(userId, location.latitude, location.longitude, city);
        break;
        
      case 'personalized':
      case 'general':
        result = await getPersonalizedLocalResponse(userId, message || '', req);
        break;
        
      default:
        return NextResponse.json({
          error: 'invalid_type',
          message: `What type of local content? News? Sports? Weather? Be specific! I'm not a mind reader!`
        }, { status: 400 });
    }
    
    if (!result.allowed) {
      return NextResponse.json({
        error: 'feature_locked',
        message: 'bubbeResponse' in result ? result.bubbeResponse : 'This feature is locked',
        requiredPlan: 'supermax',
        currentPlan: session.plan
      }, { status: 402 });
    }
    
    // Return the local content with Bubbe's commentary
    return NextResponse.json({
      success: true,
      type,
      location: {
        city,
        state: location.state,
        country: location.country
      },
      data: 'data' in result ? result.data : ('localData' in result ? result.localData : null),
      response: 'response' in result ? result.response : ('bubbeResponse' in result ? result.bubbeResponse : null),
      plan: session.plan,
      timestamp: new Date().toISOString()
    });
    
  } catch (error) {
    console.error('Local content API error:', error);
    return NextResponse.json({
      error: 'Failed to fetch local content',
      message: `Oy vey, something's broken! Even for $54 a month I can't fix everything!`
    }, { status: 500 });
  }
}

export async function GET(req: NextRequest) {
  try {
    const userId = req.cookies.get('userId')?.value ||
                   req.headers.get('x-user-id');
    
    if (!userId) {
      return NextResponse.json({
        error: 'auth_required',
        message: `Who are you? I don't talk to strangers about local gossip!`
      }, { status: 401 });
    }
    
    const session = getUserSession(userId);
    const hasAccess = session.plan === 'supermax';
    
    // Get user's location for preview
    const location = await getUserLocation(req);
    
    return NextResponse.json({
      hasAccess,
      currentPlan: session.plan,
      requiredPlan: 'supermax',
      price: 54,
      location: {
        city: location.city,
        state: location.state,
        country: location.country
      },
      features: {
        localNews: 'Get news from YOUR specific neighborhood with Bubbe commentary',
        localSports: 'Your home teams with real-time scores and Bubbe\'s hot takes',
        localWeather: 'Hyper-local weather for YOUR street, not just the city',
        personalizedInsights: 'Bubbe knows everything about your area - the gossip, the deals, the drama!'
      },
      bubbesPitch: hasAccess 
        ? `You're already on Super Max! Ask me anything about ${location.city || 'your area'}!`
        : `For $54 a month, I'll tell you EVERYTHING about ${location.city || 'your neighborhood'}! The weather on YOUR street, YOUR team's scores, and all the local gossip! Your cousin already has it!`
    });
    
  } catch (error) {
    console.error('Local content info error:', error);
    return NextResponse.json({
      error: 'Failed to get local content info'
    }, { status: 500 });
  }
}