// @blocklet/sdk/lib/util/verify-sign shim for CF Workers
//
// In Blocklet Server, component.call uses ED25519 signatures (x-component-sig)
// to authenticate inter-component calls.
//
// In CF Workers, all authentication is delegated to AUTH_SERVICE (blocklet-service)
// via the Hono caller middleware. By the time security.ts runs, the caller identity
// is already resolved and injected into req.headers['x-user-did'] / req.user.
//
// This shim delegates to AUTH_SERVICE.resolveIdentity() using the request's
// existing credentials (Cookie JWT or Authorization header), instead of
// doing local ED25519 signature verification.

export function getVerifyData(req: any, type = 'component') {
  const sig = req.get?.(`x-${type}-sig`) || req.headers?.[`x-${type}-sig`] || '';
  return { sig, data: {}, sigVersion: '', sigPk: '' };
}

export async function verify(_data: any, _sig: any): Promise<boolean> {
  // AUTH_SERVICE handles all authentication in CF Workers.
  // The Hono caller middleware (worker.ts) already called AUTH_SERVICE.resolveIdentity()
  // and injected the result into x-user-did / x-user-role headers before Express runs.
  //
  // If AUTH_SERVICE verified the caller → x-user-did is set → security.ts x-user-did path handles it.
  // If AUTH_SERVICE couldn't verify → caller is null → this path should reject.
  //
  // We return false here so the component.call path in security.ts falls through
  // to the x-user-did path, which uses the AUTH_SERVICE-resolved identity.
  const env = (globalThis as any).__CF_ENV__;
  if (env?.AUTH_SERVICE) {
    // AUTH_SERVICE is available — don't trust local signature, let the x-user-did path handle auth
    return false;
  }
  // No AUTH_SERVICE — cannot verify
  return false;
}

export default { verify, getVerifyData };
