import { jwtVerify } from "jose";

interface AuthResult {
  userId: string;
  email: string | null;
}

/**
 * Verify a Supabase JWT and extract the user ID.
 * Supabase JWTs are signed with the JWT secret and contain the user ID in the `sub` claim.
 */
export async function verifyJwt(token: string, jwtSecret: string): Promise<AuthResult> {
  const secret = new TextEncoder().encode(jwtSecret);
  const { payload } = await jwtVerify(token, secret, {
    issuer: "https://mhcafqvzbrrwvahpvvzd.supabase.co/auth/v1",
  });

  if (!payload.sub) {
    throw new Error("Missing sub claim in JWT");
  }

  return {
    userId: payload.sub,
    email: (payload.email as string) ?? null,
  };
}

/**
 * Extract Bearer token from Authorization header.
 */
export function extractToken(authHeader: string | undefined): string | null {
  if (!authHeader?.startsWith("Bearer ")) return null;
  return authHeader.slice(7);
}
