import type { NavEnv } from '../env';
import { ADMIN_SESS_PREFIX } from './constants';

/** 校验 Bearer：明文密码或 KV 会话 token */
export async function resolveAdminBearer(env: NavEnv, provided: string): Promise<boolean> {
  const secret = (env.ADMIN_PASSWORD || env.ADMIN_TOKEN || '').trim();
  if (!secret || !provided) return false;
  if (provided === secret) return true;
  const v = await env.NAV_KV.get(ADMIN_SESS_PREFIX + provided);
  return v != null && v !== '';
}

export async function verifyAuth(request: Request, env: NavEnv): Promise<boolean> {
  const auth = request.headers.get('Authorization');
  if (!auth || !auth.startsWith('Bearer ')) return false;
  const provided = auth.slice(7).trim();
  return resolveAdminBearer(env, provided);
}
