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

export const dynamic = 'force-dynamic';

const FREE_LIMIT = 5; // reads per calendar month
const monthKey = () => new Date().toISOString().slice(0, 7) + '-01';
const isSameMonth = (date: string | null | undefined) =>
  !!date && date.slice(0, 7) === new Date().toISOString().slice(0, 7);

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 jsonError(500, 'Server is misconfigured.');

  const { data: profile } = await sb
    .from('user_profiles')
    .select('tier, scan_count, scan_reset_date')
    .eq('id', user.id)
    .maybeSingle();

  const tier = (profile?.tier as 'free' | 'analyst' | 'desk') ?? 'free';
  const usedThisMonth = isSameMonth(profile?.scan_reset_date) ? (profile?.scan_count ?? 0) : 0;
  const remaining = tier === 'free' ? Math.max(0, FREE_LIMIT - usedThisMonth) : null;

  return NextResponse.json({
    tier,
    used_this_month: usedThisMonth,
    remaining,
    limit: tier === 'free' ? FREE_LIMIT : null,
    reset_date: monthKey(),
    period: 'monthly',
  });
}
