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

  const { data, error } = await sb
    .from('user_profiles')
    .select('id, email, tier, scan_count, scan_reset_date, subscription_status, subscription_end, founder_pricing, cancel_at_period_end')
    .eq('id', user.id)
    .maybeSingle();

  if (error) {
    return jsonError(500, error.message);
  }
  return NextResponse.json(data ?? { id: user.id, email: user.email, tier: 'free' });
}

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

  let body: { age_verified?: boolean; cancel_at_period_end?: boolean };
  try {
    body = await req.json();
  } catch {
    return jsonError(400, 'Invalid JSON body.');
  }

  const sb = getServiceRoleSupabase();
  if (!sb) return jsonError(500, 'Server is misconfigured.');

  const update: Record<string, unknown> = {};
  if (typeof body.age_verified === 'boolean') update.age_verified = body.age_verified;
  if (typeof body.cancel_at_period_end === 'boolean') update.cancel_at_period_end = body.cancel_at_period_end;

  if (Object.keys(update).length === 0) return jsonError(400, 'Nothing to update.');

  const { data, error } = await sb
    .from('user_profiles')
    .update(update)
    .eq('id', user.id)
    .select()
    .single();

  if (error) return jsonError(500, error.message);
  return NextResponse.json(data);
}
