import { NextRequest } from 'next/server';
import { getServerSupabase } from './supabase';

export interface AuthedUser {
  id: string;
  email: string | null;
  tier: 'free' | 'analyst' | 'desk';
}

/**
 * Verify a bearer token from the Authorization header against Supabase.
 * Returns null when missing/invalid — callers decide whether to 401.
 */
export async function getUserFromRequest(req: NextRequest): Promise<AuthedUser | null> {
  const auth = req.headers.get('authorization');
  if (!auth || !auth.toLowerCase().startsWith('bearer ')) return null;

  const sb = getServerSupabase(auth);
  if (!sb) return null;

  const { data, error } = await sb.auth.getUser();
  if (error || !data.user) return null;

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

  return {
    id: data.user.id,
    email: data.user.email ?? null,
    tier: ((profile?.tier as AuthedUser['tier']) ?? 'free'),
  };
}

export function jsonError(status: number, message: string) {
  return Response.json({ error: message }, { status });
}
