import { NextRequest, NextResponse } from 'next/server';
import { getServiceRoleSupabase } from '@/lib/supabase';

export const dynamic = 'force-dynamic';

interface Body {
  sport?: 'NBA' | 'MLB' | 'WNBA';
  player?: string;
  stat?: string;
  line?: number;
  direction?: 'over' | 'under';
}

const VALID_SPORTS = new Set(['NBA', 'MLB', 'WNBA']);
const VALID_DIRS = new Set(['over', 'under']);

export async function POST(req: NextRequest) {
  let body: Body;
  try {
    body = (await req.json()) as Body;
  } catch {
    return NextResponse.json({ error: 'Invalid JSON.' }, { status: 400 });
  }

  if (
    !body.sport || !VALID_SPORTS.has(body.sport) ||
    !body.player || typeof body.player !== 'string' ||
    !body.stat ||
    typeof body.line !== 'number' || !Number.isFinite(body.line) ||
    !body.direction || !VALID_DIRS.has(body.direction)
  ) {
    return NextResponse.json({ error: 'Missing or invalid leg fields.' }, { status: 400 });
  }

  const sb = getServiceRoleSupabase();
  if (!sb) return NextResponse.json({ ok: true, persisted: false });

  // RPC increments scan or parlay counter atomically.
  await sb.rpc('increment_parlay_leg_frequency', {
    p_player: body.player,
    p_stat: body.stat,
    p_line: body.line,
    p_dir: body.direction,
    p_sport: body.sport,
    p_scan_delta: 0,
    p_parlay_delta: 1,
  });

  return NextResponse.json({ ok: true });
}
