import { NextRequest, NextResponse } from 'next/server';
import { getUserFromRequest, jsonError } from '@/lib/auth-helpers';
import { getServiceRoleSupabase } from '@/lib/supabase';

export const dynamic = 'force-dynamic';

export async function GET(req: NextRequest) {
  const user = await getUserFromRequest(req);
  if (!user) return jsonError(401, 'Not signed in.');

  const sb = getServiceRoleSupabase();
  if (!sb) return NextResponse.json({ scans: [] });

  const { data, error } = await sb
    .from('scan_history')
    .select('id, sport, player_name, stat, line, direction, grade, created_at')
    .eq('user_id', user.id)
    .order('created_at', { ascending: false })
    .limit(10);

  if (error) return jsonError(500, error.message);
  return NextResponse.json({ scans: data ?? [] });
}
